1. 程式人生 > >C#設計模式-工廠方法模式

C#設計模式-工廠方法模式

using System;

namespace TestCS
{
    class Program
    {
        static void Main(string[] args)
        {
            CarFactory factory0 = new CarFactory();
            Vehicle vehicle0 = factory0.CreateVechicle(); 
            Console.WriteLine("Create Vehicle " + vehicle0.GetName());

            BicycleFactory factory1 = new BicycleFactory();
            Vehicle vehicle1 = factory1.CreateVechicle();
            Console.WriteLine("Create Vehicle " + vehicle1.GetName());

            Console.ReadKey();
        }
    }

    abstract class Factory
    {
        public abstract Vehicle CreateVechicle();
    }

    class CarFactory : Factory
    {
        public override Vehicle CreateVechicle()
        {
            return new Car();
        }
    }

    class BicycleFactory : Factory
    {
        public override Vehicle CreateVechicle()
        {
            return new Bicycle();
        }
    }

    abstract class Vehicle
    {
        public virtual string GetName()
        {
            return string.Empty;
        }
    }

    class Car : Vehicle
    {
        public override string GetName()
        {
            return "Car";
        }
    }

    class Bicycle : Vehicle
    {
        public override string GetName()
        {
            return "Bicycle";
        }
    }
}