天天看點

備忘錄模式

/*

 *

 * user: administrator

 * date: 2007-7-2

 * time: 9:02

 */

using system;

using system.collections.generic;

namespace mymemonto

{

    public interface imemonto{}

    public class state

    {

        public state(){}

        public string statename;//狀态名

        public int level;//狀态級别

    }

    //發起者

    public class originator

        private class memonto:imemonto

        {

            private state _state;

            public memonto(state st)

            {

                _state=new state();

                _state.statename=st.statename;

                _state.level=st.level;

            }

        public state state

            get{

                return _state;

            set{

                _state=value;

        }

        private state state;

        public originator()

            state=new state();

            state.statename="begin";

            state.level=1;

        public string statename

            get{return state.statename;}

            set{state.statename=value;}

        public int level

            get

                return state.level;

            set

                state.level=value;

        public imemonto createmomento()    {

            return new memonto(this.state);

        public void setstate(imemonto m)

            memonto mm=(memonto)m;

            this.state=mm.state;

    public class caretaker:system.collections.collectionbase

        public caretaker(){}

        public int add(imemonto st)

            return list.add(st);

        public imemonto this[int index]{

                return (imemonto)list[index];

                list[index]=value;

        public void remove(imemonto st){

            list.remove(st);

        public imemonto restore()

            if(list.count==0) return null;

            imemonto st=(imemonto) list[list.count-1];

            return st;

    class mainclass

        public static void main(string[] args)

            //console.writeline("hello world!");

            originator o=new originator();

            caretaker c=new caretaker();

            c.add(o.createmomento());

            o.statename="one";

            o.level=100;

            o.statename="two";

            o.level=200;

            imemonto m=c.restore();

            while(m!=null){

                o.setstate(m);

                system.console.writeline(o.statename);

                m=c.restore();

            system.console.readline();

}