설계 모드 정선 실례

5034 단어
단일 모드:
//  Demo
public sealed class Singleton
{
    private static readonly Singleton instance = new Singleton();

    private Singleton()
    {
    }

    public static Singleton GetInstance()
    {
        return instance;
    }

    public string GetKey()
    {
        return "abcdefg";
    }
}

//  
Singleton s1 = Singleton.GetInstance();

Response.Write(s1.GetKey());

추상 공장 모드:
/*               ,                  
        ,                            
          ,                 ,                */
    public abstract class Product
    {
        public abstract void work();
    }
    public class ProductA : Product
    {
        public override void work()
        {
            Console.Write("ProductA");
        }
    }
    public class ProductB : Product
    {
        public override void work()
        {
            Console.Write("ProductB");
        }
    }
    public abstract class Car
    {
        public abstract void Build();
    }
    public class CarA : Car
    {
        public override void Build()
        {
            Console.Write("Build CarA");
        }
    }
    public class CarB : Car
    {
        public override void Build()
        {
            Console.Write("Build CarB");
        }
    }
    public abstract class AbstractFactory
    {
        //        
        public abstract Product newproduct();
        public abstract Car newCar();
    }
    public class AbstractFactoryA : AbstractFactory
    {
        public override Product newproduct()
        {
            return new ProductA();//            
        }
        public override Car newCar()
        {
            return new CarA();
        }
    }
    public class AbstractFactoryB : AbstractFactory
    {
        public override Product newproduct()
        {
            return new ProductB();//            
        }
        public override Car newCar()
        {
            return new CarB();
        }
    }

    public class AbstractFactoryClient
    {
        public static void GetFactoryMethod()
        {
            AbstractFactory factorysubA = new AbstractFactoryA();
            AbstractFactory factorysubB = new AbstractFactoryA();

            Product pruductA = factorysubA.newproduct();
            Product pruductB = factorysubB.newproduct();
            Car factorycarA = factorysubA.newCar();

            factorycarA.Build();

            pruductA.work();
            pruductB.work();
        }
    }

좋은 웹페이지 즐겨찾기