zoukankan      html  css  js  c++  java
  • [置顶]c# 设计模式(1)一 创建型

    为了方便阅读,我把一篇设计模式的资料拆分开发,分为三个大的部分,如下:

     

    名称

    Factory Method

    结构

     

    意图

    定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method 使一个类的实例化延迟到其子类。

    适用性

    • 当一个类不知道它所必须创建的对象的类的时候。
    • 当一个类希望由它的子类来指定它所创建的对象的时候。
    • 当类将创建对象的职责委托给多个帮助子类中的某一个,并且你希望将哪一个帮助子类是代理者这一信息局部化的时候。

    Code Example

    namespace FactoryMethod_DesignPattern

    {

        using System;

     

              // These two classes could be part of a framework,

              // which we will call DP

              // ===============================================

             

              class DPDocument

              {

             

     

              }

     

              abstract class DPApplication

              {

                        protected DPDocument doc;

                       

                        abstract public void CreateDocument();

     

                        public void ConstructObjects()

                        {

                                  

                                   // Create objects as needed

                                   // . . .

     

                                   // including document

                                   CreateDocument();

                        }                  

                        abstract public void Dump();

              }

     

              // These two classes could be part of an application

              // =================================================

     

              class MyApplication : DPApplication

              {

                        override public void CreateDocument()

                        {

                                   doc = new MyDocument();                           

                        }                             

     

                        override public void Dump()

                        {

                                   Console.WriteLine("MyApplication exists");

                        }

              }        

     

              class MyDocument : DPDocument

              {

     

              }

     

        /// <summary>

        ///    Summary description for Client.

        /// </summary>

        public class Client

        {

            public static int Main(string[] args)

            {

                MyApplication myApplication = new MyApplication();

     

                                   myApplication.ConstructObjects();

     

                                   myApplication.Dump();

                                  

                return 0;

            }

        }

    }

     

     

    名称

    Abstract Factory

    结构

    意图

    提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。

    适用性

    • 一个系统要独立于它的产品的创建、组合和表示时。
    • 一个系统要由多个产品系列中的一个来配置时。
    • 当你要强调一系列相关的产品对象的设计以便进行联合使用时。
    • 当你提供一个产品类库,而只想显示它们的接口而不是实现时。

    Code Example

    namespace AbstractFactory_DesignPattern
    {
        using System;
     
              // These classes could be part of a framework,
              // which we will call DP
              // ===========================================
              
              abstract class DPDocument 
              {
                        abstract public void Dump();             
              }
     
              abstract class DPWorkspace
              {
                        abstract public void Dump();
              }
              
              abstract class DPView 
              {
                        abstract public void Dump();
              }         
              
              abstract class DPFactory 
              {
                        abstract public DPDocument CreateDocument();
                        abstract public DPView CreateView();
                        abstract public DPWorkspace CreateWorkspace();
              }
     
              abstract class DPApplication 
              {
                        protected DPDocument doc;
                        protected DPWorkspace workspace;
                        protected DPView view;
                        
                        public void ConstructObjects(DPFactory factory)
                        {
                                   // Create objects as needed
                                   doc = factory.CreateDocument();
                                   workspace = factory.CreateWorkspace();
                                   view = factory.CreateView();
                        }                   
                        
                        abstract public void Dump();
     
                        public void DumpState()
                        {
                                   if (doc != null) doc.Dump();
                                   if (workspace != null) workspace.Dump();
                                   if (view != null) view.Dump();
                        }
              }
     
              // These classes could be part of an application 
              class MyApplication : DPApplication 
              {
                        MyFactory myFactory = new MyFactory();
     
                        override public void Dump()
                        {
                                   Console.WriteLine("MyApplication exists");
                        }
     
                        public void CreateFamily()
                        {
                                   MyFactory myFactory = new MyFactory();
                                   ConstructObjects(myFactory);                       
                        }
              }         
     
              class MyDocument : DPDocument 
              {
                        public MyDocument()
                        {
                                             Console.WriteLine("in MyDocument constructor");                      
                        }
                        
                        override public void Dump()
                        {
                                   Console.WriteLine("MyDocument exists");
                        }
              }
     
              class MyWorkspace : DPWorkspace 
              {
                        override public void Dump()
                        {
                                   Console.WriteLine("MyWorkspace exists");
                        }
              }
     
              class MyView : DPView 
              {
                        override public void Dump()
                        {
                                   Console.WriteLine("MyView exists");
                        }
              }
     
              class MyFactory : DPFactory 
              {
                        override public DPDocument CreateDocument()
                        {
                                   return new MyDocument();
                        }
                        override public DPWorkspace CreateWorkspace()
                        {
                                   return new MyWorkspace();
                        }                   
                        override public DPView CreateView()
                        {
                                   return new MyView();
                        }
              }
     
        /// <summary>
        ///    Summary description for Client.
        /// </summary>
        public class Client
        {
            public static int Main(string[] args)
            {
                                   MyApplication myApplication = new MyApplication();
     
                                   myApplication.CreateFamily();
     
                                   myApplication.DumpState();
                                   
                return 0;
            }
        }
    }

     

    名称

    Builder

    结构

    意图

    将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。

    适用性

    • 当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时。
    • 当构造过程必须允许被构造的对象有不同的表示时。

    Code Example

    namespace Builder_DesignPattern
    {
        using System;
     
              // These two classes could be part of a framework,
              // which we will call DP
              // ===============================================
              
              class Director 
              {
                        public void Construct(AbstractBuilder abstractBuilder)
                        {
                                   abstractBuilder.BuildPartA();
                                   if (1==1 ) //represents some local decision inside director
                                   {
                                             abstractBuilder.BuildPartB();                      
                                   }
                                   abstractBuilder.BuildPartC();                      
                        }
     
              }
     
              abstract class AbstractBuilder 
              {
                        abstract public void BuildPartA();
                        abstract public void BuildPartB();
                        abstract public void BuildPartC();
              }
     
              // These two classes could be part of an application 
              // =================================================
     
              class ConcreteBuilder : AbstractBuilder 
              {
                        override public void BuildPartA()
                        {
                                   // Create some object here known to ConcreteBuilder
                                   Console.WriteLine("ConcreteBuilder.BuildPartA called");
                        }
                                             
                        override public void BuildPartB()
                        {
                                   // Create some object here known to ConcreteBuilder
                                   Console.WriteLine("ConcreteBuilder.BuildPartB called");
                        }
                        
                        override public void BuildPartC()
                        {
                                   // Create some object here known to ConcreteBuilder
                                   Console.WriteLine("ConcreteBuilder.BuildPartC called");
                        }
              }         
     
        /// <summary>
        ///    Summary description for Client.
        /// </summary>
        public class Client
        {
            public static int Main(string[] args)
            {
                ConcreteBuilder concreteBuilder = new ConcreteBuilder();
                                   Director director = new Director();
     
                                   director.Construct(concreteBuilder);
     
                return 0;
            }
        }
    }

     

    名称

    Prototype

    结构

    意图

    用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

    适用性

    • 当要实例化的类是在运行时刻指定时,例如,通过动态装载;或者
    • 为了避免创建一个与产品类层次平行的工厂类层次时;或者
    • 当一个类的实例只能有几个不同状态组合中的一种时。建立相应数目的原型并克隆它们可能比每次用合适的状态手工实例化该类更方便一些。

    Code Example

    namespace Prototype_DesignPattern

    {

        using System;

     

              // Objects which are to work as prototypes must be based on classes which

              // are derived from the abstract prototype class

              abstract class AbstractPrototype

              {

                        abstract public AbstractPrototype CloneYourself();

              }

     

              // This is a sample object

              class MyPrototype : AbstractPrototype

              {

                        override public AbstractPrototype CloneYourself()

                        {

                                   return ((AbstractPrototype)MemberwiseClone());

                        }

                        // lots of other functions go here!

              }

     

              // This is the client piece of code which instantiate objects

              // based on a prototype.

              class Demo

              {

                        private AbstractPrototype internalPrototype;

     

                        public void SetPrototype(AbstractPrototype thePrototype)

                        {

                                   internalPrototype = thePrototype;                           

                        }

     

                        public void SomeImportantOperation()

                        {

                                   // During Some important operation, imagine we need

                                   // to instantiate an object - but we do not know which. We use

                                   // the predefined prototype object, and ask it to clone itself.

     

                                   AbstractPrototype x;

                                   x = internalPrototype.CloneYourself();

                                   // now we have two instances of the class which as as a prototype

                        }

              }

     

        /// <summary>

        ///    Summary description for Client.

        /// </summary>

        public class Client

        {

            public static int Main(string[] args)

            {                                         

                                   Demo demo = new Demo();

                                   MyPrototype clientPrototype = new MyPrototype();

                                   demo.SetPrototype(clientPrototype);

                                   demo.SomeImportantOperation();

     

                                   return 0;

            }

        }

    }

     

    名称

    Singleton

    结构

    意图

    保证一个类仅有一个实例,并提供一个访问它的全局访问点。

    适用性

    • 当类只能有一个实例而且客户可以从一个众所周知的访问点访问它时。
    • 当这个唯一实例应该是通过子类化可扩展的,并且客户应该无需更改代码就能使用一个扩展的实例时。

    Code Example

    namespace Singleton_DesignPattern

    {

        using System;

     

              class Singleton

              {

                        private static Singleton _instance;

                       

                        public static Singleton Instance()

                        {

                                   if (_instance == null)

                                             _instance = new Singleton();

                                   return _instance;

                        }

                        protected Singleton(){}

     

                        // Just to prove only a single instance exists

                        private int x = 0;

                        public void SetX(int newVal) {x = newVal;}

                        public int GetX(){return x;}            

              }

     

        /// <summary>

        ///    Summary description for Client.

        /// </summary>

        public class Client

        {

            public static int Main(string[] args)

            {

                int val;

                                   // can't call new, because constructor is protected

                                   Singleton FirstSingleton = Singleton.Instance();

                                   Singleton SecondSingleton = Singleton.Instance();

     

                                   // Now we have two variables, but both should refer to the same object

                                   // Let's prove this, by setting a value using one variable, and

                                   // (hopefully!) retrieving the same value using the second variable

                                   FirstSingleton.SetX(4);

                                   Console.WriteLine("Using first variable for singleton, set x to 4");          

     

                                   val = SecondSingleton.GetX();

                                   Console.WriteLine("Using second variable for singleton, value retrieved = {0}", val);                 

                return 0;

            }

        }

    }

  • 相关阅读:
    怎么导出SQL所有用户表的字段信息
    全面掌握C#中的拖放操作
    C#中使用Hook(钩子)
    如何在winform程序中显示网页
    设置socket.Receive()的等待时延
    局域网QQ(C#版)
    C#实现系统热键的功能
    使用C#在应用程序间发送消息
    某某人整理的c#.net函数列表
    C#串口通信编程类(修改版)
  • 原文地址:https://www.cnblogs.com/encounter/p/2188765.html
Copyright © 2011-2022 走看看