工廠模式示例程式碼

ilovewebservice發表於2011-03-28

abstract class Car

     {

        public abstract void Startup();

        public abstract void Run();

        public abstract void Turn(Direction direction);

        public abstract void Stop();

     }

    //CarFactory.cs

    abstract class CarFactory

    {

        public abstract Car CreateCar();

    }

    //HongqiCar.cs

    public class HongqiCar : AbstractCar

    {

        Enginee enginee1;

        Enginee enginee2;

        Enginee enginee3;

        Enginee enginee4;

        public override void Startup()

        {

        }

        public override void Run()

        {

        }

        public override void Turn(Direction direction)

        {

        }

        public override void Stop()

        {

        }

    }

    public class HongqiCarFactory : CarFactory

    {

        public override Car CreateCar()

        {

            return new HongqiCar();

        }

    }

    //CarTestFramewrok.cs

    class CarTestFrameWork

    {

        public void BuildTestContext(CarFactory carFactory)

        {

            AbstractCar c1 = carFactory.CreateCar();

            AbstractCar c2 = carFactory.CreateCar();

            AbstractCar c3 = carFactory.CreateCar();

            AbstractCar c4 = carFactory.CreateCar();

        }

        public void DoTest(AbstractCar car)

        {

            car.Run();

        }

        public TestData GetTestData(AbstractCar car)

        {

            car.Stop();

        }

    }

    //App.cs

    class App

    {

        public static void Main()

        {

            CarTestFrameWork carTestFrameWork = new CarTestFrameWork();

            //這裡可以用反射做

            carTestFrameWork.BuildTestContext(new HongqiCarFactory());

        }

}

 

相關文章