博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c# 设计模式(一)创建型
阅读量:5256 次
发布时间:2019-06-14

本文共 10151 字,大约阅读时间需要 33 分钟。

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

 

 

 

名称

Factory Method

结构

 

意图

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

适用性

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

Code Example

 

 

 

名称

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 description for Client.
    /// 
    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 description for Client.
    /// 
    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;

        }

    }

}

 

转载于:https://www.cnblogs.com/hliq/archive/2011/07/14/2106692.html

你可能感兴趣的文章
jquery的contains方法
查看>>
linux后台运行和关闭SSH运行,查看后台任务
查看>>
桥接模式-Bridge(Java实现)
查看>>
303. Range Sum Query - Immutable
查看>>
C# Dynamic通用反序列化Json类型并遍历属性比较
查看>>
前台freemark获取后台的值
查看>>
Spring-hibernate整合
查看>>
exit和return的区别
查看>>
Django 相关
查看>>
Python(软件目录结构规范)
查看>>
codeforces水题100道 第二十二题 Codeforces Beta Round #89 (Div. 2) A. String Task (strings)
查看>>
c++||template
查看>>
条件断点 符号断点
查看>>
.net学习之继承、里氏替换原则LSP、虚方法、多态、抽象类、Equals方法、接口、装箱拆箱、字符串------(转)...
查看>>
python的多行注释
查看>>
连接Oracle需要jar包和javadoc文档的下载
查看>>
Dreamweaver cc新版本css单行显示
查看>>
【android】安卓的权限提示及版本相关
查看>>
Java基础教程——网络基础知识
查看>>
Kruskal基础最小生成树
查看>>