原型模式示例程式碼

ilovewebservice發表於2011-03-28

模擬在遊戲裡建立不同種類的怪物

    //抽象類

    public abstract class NormalActor

    {

        public abstract NormalActor Clone();

    }

    //抽象類

    public abstract class FlyActor

    {

        public abstract FlyActor Clone();

    }

    //抽象類

    public abstract class WaterActor

    {

        public abstract WaterActor Clone();

    }

    public class NormalActorA : NormalActor

    {

        public override NormalActor Clone()

        {

            //注意這裡是淺拷貝,深拷貝可以用序列化來實現

            return (NormalActor)this.MemberwiseClone();

        }

    }

    public class NormalActorB : NormalActor

    {

        public override NormalActor Clone()

        {

            //注意這裡是淺拷貝,深拷貝可以用序列化來實現

            return (NormalActor)this.MemberwiseClone();

        }

    }

    public class FlyActorA : FlyActor

    {

        public override FlyActor Clone()

        {

            //注意這裡是淺拷貝,深拷貝可以用序列化來實現

            return (FlyActor)this.MemberwiseClone();

        }

    }

    public class FlyActorB : FlyActor

    {

        public override FlyActor Clone()

        {

            //注意這裡是淺拷貝,深拷貝可以用序列化來實現

            return (FlyActor)this.MemberwiseClone();

        }

    }

    public class WaterActorA : WaterActor

    {

        public override WaterActor Clone()

        {

            //注意這裡是淺拷貝,深拷貝可以用序列化來實現

            return (WaterActor)this.MemberwiseClone();

        }

    }

    public class WaterActorB : WaterActor

    {

        public override WaterActor Clone()

        {

            //注意這裡是淺拷貝,深拷貝可以用序列化來實現

            return (WaterActor)this.MemberwiseClone();

        }

    }

    public class GameSystem

     {

        public void Run(NormalActor normalActor, FlyActor flyActor, WaterActor waterActor)

        {

            NormalActor normalActor1 = normalActor.Clone();

            NormalActor normalActor2 = normalActor.Clone();

            NormalActor normalActor3 = normalActor.Clone();

            NormalActor normalActor4 = normalActor.Clone();

            NormalActor normalActor5 = normalActor.Clone();

            FlyActor flyActor1 = flyActor.clone();

            FlyActor flyActor2 = flyActor.clone();

            WaterActor waterActor1 = waterActor.clone();

            WaterActor waterActor2 = waterActor.clone();

        }

     }

    class App

    {

        public static void Main()

        {

            GameSystem gameSystem = new GameSystem();

            gameSystem.run(new NormalActorA(), new FlyActorB(), new WaterActorA());

        }

}

 

相關文章