zoukankan      html  css  js  c++  java
  • 常用的設計模式

    设计模式是软件开发讨论中,亘古不变的话题,今天又拿出来说道两句,也是对设计模式的一个复习吧。


    工厂方法模式

           工厂方法模型定义了一个用于创建对象的接口,让子类决定实例化哪一个类,工厂模式使一个类的实例化延迟到了其子类中。工厂方法模式是优化的简单工厂模式,它很好的支持了“开闭原则”。每一个具体的工厂只能构建一个类的对象。具体工厂类与产品类是一对一的关系。

     

    1. /// <summary>    
    2. /// 抽象产品类  
    3. /// </summary>    
    4. public class Product{  
    5.     public Product(){  
    6.         Console.Write("new Product");  
    7.     }   
    8. }  
    9.   
    10. /// <summary>    
    11. /// 具体产品类A  
    12. /// </summary>  
    13. public class ConcreteProductA:Product {  
    14.     public ConcreteProduct(){  
    15.         Console.Write("创建了一个 ConcreteProductA");  
    16.     }  
    17. }  
    18.   
    19. /// <summary>    
    20. /// 具体产品类B  
    21. /// </summary>  
    22. public class ConcreteProductB:Product {  
    23.     public ConcreteProduct(){  
    24.         Console.Write("创建了一个 ConcreteProductB");  
    25.     }  
    26. }  
    27.   
    28. /// <summary>    
    29. /// 抽象的创建者  
    30. /// </summary>  
    31. abstract public class Creator{  
    32.       
    33.     //抽象的工厂方法  
    34.     public abstract Product FactoryMethod();  
    35.       
    36. }  
    37.   
    38. /// <summary>    
    39. /// 具体方法工厂A  
    40. /// </summary>  
    41. public class ConcreteCreatorA:Creator{  
    42.     //返回一个产品A的对象  
    43.     public override Product FactoryMethod(){  
    44.         return new ConcreteProductA();  
    45.     }  
    46. }  
    47.   
    48. /// <summary>    
    49. /// 具体方法工厂B  
    50. /// </summary>  
    51. public class ConcreteCreatorB:Creator{  
    52.     //返回一个产品B的对象  
    53.     public override Product FactoryMethod(){  
    54.         return new ConcreteProductB();  
    55.     }  
    56. }  
    57.   
    58. //client端  
    59. static void Main(string[] args)    
    60. {    
    61.     Creator c = new ConcreteCreatorA();  
    62.     Product p = c.FcatoryMethod();  
    63.       
    64.     c = new ConcreteCreatorB();  
    65.     p = c.FcatoryMethod();  
    66.       
    67.     Console.ReadLine();  
    68. }   



     

    适配器模式Adapter

          适配器模式是将一个类的接口转换成客户希望的另外一个接口。适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

          两个成熟的类需要通信,但是接口不同,由于开闭原则,我们不能去修改这两个类的接口,所以就需要一个适配器来完成衔接过程。

          变压器就是很好的适配器模式的例子。用电设备所需要的电压是9V,但是电线上的 电压却是220V的,我们不能去更改它们的电压输入或输出,所以我们用到了变压器。变压器是220V的输入,9V的输出。这样就可以将200V的电压变为 9V的电压,用变压器将用电设备连接到了电线上工作了。

           上面两幅图中,都是Client端需要Request这个方法,但是Adaptee没有这个方法,所以就需要提供一个中间件/包装类 (Wrapper)Adapter类来衔接。不同的是第一幅图Adapter继承自Adaptee,而第二幅图是在Adapter类中包装了一个 Adaptee的实例。这就决定了第一幅图讲的是“类的结构模式”,而第二幅图则是“对象的结构模式”。

     

    1. /// <summary>    
    2. /// 目标接口,客户所期待的接口。  
    3. /// </summary>   
    4. public class Target{  
    5.     public virtual void Request(){  
    6.         Console.Write("我是本系统中的普通请求.");  
    7.     }  
    8.       
    9. }  
    10.   
    11. /// <summary>    
    12. /// 适配器,匹配2个接口不一致的类  
    13. /// </summary>   
    14. public class Adapter:Target{  
    15.     private Adaptee adaptee = new Adaptee();  
    16.     public void Request(){  
    17.         adaptee.SpecificRequest();  
    18.     }  
    19. }  
    20.   
    21. /// <summary>    
    22. /// 源接口,与客户期待的接口不一致  
    23. /// </summary>   
    24. public class Adaptee(){  
    25.     public void SpecificRequest(){  
    26.         Console.Write("我是原有的真实调用的系统");  
    27.     }  
    28. }  
    29.   
    30. //client端  
    31. static void Main(string[] args)    
    32. {    
    33.     Target t = new Adapter();  
    34.     t.Request();  
    35.       
    36.     Console.ReadLine();  
    37. }   


    桥接模式 Bridge

          桥接模式将抽象部分与它的实现部分分离,使它们都可以独立地变化。它很好的支持了开闭原则和组合及复用原则。实现系统可能有多角度分类,每一种分类都有可能变化,那么就把这些多角度分离出来让他们独立变化,减少他们之间的耦合。

          2个相互耦合的系列,每个系列都有各自的产品变动。将这2个系列抽象成2个角色类,将各自的变化封装到对象的角色类中,然后再将2个角色类之间用组合的关系表示,这样就大大简化了使用类继承的复杂性,逻辑变得清晰了,易于扩展和维护。

          桥接模式封装了变化,完成了解耦,实现了弱耦合。

     

    1. /// <summary>    
    2. /// 抽象部分  
    3. /// </summary>   
    4. public class Abstraction{  
    5.     protected Implementor implementor;  
    6.       
    7.     public void SetImplementor(Implementor implementor){  
    8.         this.implementor = implementor;  
    9.     }  
    10.       
    11.     public virtual void Operation(){  
    12.         implementor.OperationImp();  
    13.     }  
    14. }  
    15.   
    16. /// <summary>    
    17. /// 被提炼的抽象部分  
    18. /// </summary>   
    19. public class RefinedAbstraction:Abstraction{  
    20.       
    21.     public override void Operation(){  
    22.         implementor.OperationImp();  
    23.     }  
    24. }  
    25.   
    26. /// <summary>    
    27. /// 实现部分  
    28. /// </summary>   
    29. abstract public class Implementor{  
    30.     public abstract void OperationImp();  
    31. }  
    32.   
    33. /// <summary>    
    34. /// 具体实现A  
    35. /// </summary>   
    36. public class conscreteImplementorA:Implementor{  
    37.     pulic override void OperationImp(){  
    38.         Console.Write("我是具体的A");  
    39.     }  
    40. }  
    41.   
    42. /// <summary>    
    43. /// 具体实现B  
    44. /// </summary>   
    45. public class conscreteImplementorB:Implementor{  
    46.     pulic override void OperationImp(){  
    47.         Console.Write("我是具体的B");  
    48.     }  
    49. }  
    50. //client端  
    51. static void Main(string[] args)    
    52. {    
    53.     Abstraction ab = new RefinedAbstraction();  
    54.     ab.SetImplementor(new conscreteImplementorA());  
    55.     ab.Operaton();  
    56.       
    57.     ab.SetImplementor(new conscreteImplementorB());  
    58.     ab.Operaton();  
    59.       
    60.     Console.ReadLine();  
    61. }   

    具体的实例可以看我的另一篇博文《面与卤的鹊桥相会——桥接模式

    装饰模式 Decorator

           装饰模式动态地给一个对象添加一些额外的职责,就增加功能来说,它比生成子类更灵活。也可以这样说,装饰模式把复杂类中的核心职责和装饰功能区分开了,这样既简化了复杂类,有去除了相关类中重复的装饰逻辑。装饰模式没有通过继承原有类来扩展功能,但却达到了一样的目的,而且比继承更加灵活,所以可以说装饰模式是继承关系的一种替代方案。装饰模式解耦了核心和装饰功能,所以也是强调了松耦合。 

     

    1. /// <summary>    
    2. /// 最高接口,被装饰者和“装饰品”都继承于此  
    3. /// </summary>   
    4. abstract public class Component{  
    5.     public abstract void Operation();  
    6. }  
    7.   
    8. /// <summary>    
    9. /// 具体的被装饰者  
    10. /// </summary>   
    11. public class Concretecomponent:Component{  
    12.     public override void Operation(){  
    13.         Console.Write("具体对象的装饰操作");  
    14.     }  
    15. }  
    16.   
    17. /// <summary>    
    18. /// 装饰类  
    19. /// </summary>   
    20. abstract public class Decorator:Component(){  
    21.     protected Component component;  
    22.       
    23.     public void SetComponent(Component component){  
    24.         this.component = component;  
    25.     }  
    26.     public override void Operation(){  
    27.         if(component!=null) component.Operation();  
    28.     }  
    29. }  
    30.   
    31. /// <summary>    
    32. /// 具体的装饰类A  
    33. /// </summary>   
    34. public class ConcreteDecoratorA:Decorator{  
    35.     private string addedState;  
    36.     public override void Operation(){  
    37.         base.Operation();  
    38.         addedState="New State";  
    39.         Console.Write("具体装饰A的操作(添加了新的状态)");  
    40.     }  
    41. }  
    42.   
    43. /// <summary>    
    44. /// 具体的装饰类B  
    45. /// </summary>   
    46. public class ConcreteDecoratorB:Decorator{  
    47.     public override void Operartion(){  
    48.         base.Operation();  
    49.         AddedBehavior();  
    50.         Console.WriteLine("具体装饰B的操作(添加了新的方法)");  
    51.     }  
    52.     private void AddedBehavior(){  
    53.         //添加新的行为  
    54.     }  
    55. }  
    56.   
    57. //client端  
    58. static void Main(string[] args)    
    59. {    
    60.     Concretecomponent c = new Concretecomponent();  
    61.     Decorator d1 = new ConcreteDecoratorA();  
    62.     Decorator d2 = new ConcreteDecoratorB();  
    63.       
    64.     d1.SetComponent(c);  
    65.     d2.SetComponent(d1);//注意这里装饰的是d1,因为这里的d1是装饰了d1的c。  
    66.     d2.Operation();  
    67.       
    68.     Console.ReadLine();  
    69. }   


    外观模式 Facade

           外观模式为子系统中的一组接口提供了一个一致的界面,此模式定义了一个高层接口,这个接口使得这些子系统更加容易使用。

           外观模式中,客户对各个具体的子系统是不了解的,所以对这些子系统进行了封装,对外只提供了用户所明白的单一而简单的接口,用户直接使用这个接口就可以完成操作,而不用去理睬具体的过程,而且子系统的变化不会影响到用户,这样就做到了信息隐蔽。

           这就相当于新生接待员。新生对入学流程不清楚,但是接待员学长可是明白的。学生跟着接待员就可以把各个手续办理完毕了。可以说外观模式封装了细节

     

    1. /// <summary>    
    2. /// 高层的统一接口,封装了子系统繁杂的接口。  
    3. /// </summary>   
    4. public class Facade{  
    5.     private SubSystemOne one;  
    6.     private SubSystemTwo two;  
    7.     private SubSystemThree three;  
    8.       
    9.     public Facade(){  
    10.         one = new SubSystemOne();  
    11.         two = new SubSystemTwo();  
    12.         three = new SubSystemThree();  
    13.     }  
    14.       
    15.     public void MethodA(){  
    16.         one.MethodOne();  
    17.         two.MethodTwo();  
    18.     }  
    19.       
    20.     public void MethodB(){  
    21.         one.MethodOne();  
    22.         three.MethodThree();  
    23.     }  
    24.       
    25. }  
    26.   
    27. /// <summary>    
    28. /// 子系统One。  
    29. /// </summary>   
    30. public class SubSystemOne{  
    31.     public void MethodOne(){  
    32.         Console.Write("我是One");  
    33.     }  
    34. }  
    35.   
    36. /// <summary>    
    37. /// 子系统Two  
    38. /// </summary>   
    39. public class SubSystemTwo{  
    40.     public void MethodTwo(){  
    41.         Console.Write("我是Two");  
    42.     }  
    43. }  
    44.   
    45. /// <summary>    
    46. /// 子系统Three  
    47. /// </summary>   
    48. public class SubSystemThree{  
    49.     public void MethodThree(){  
    50.         Console.Write("我是Three");  
    51.     }  
    52. }  
    53.   
    54. //client端  
    55. static void Main(string[] args)    
    56. {  
    57.     Facade f1 = new Facade();  
    58.     f1.MethodA();  
    59.       
    60.     Facade f2 = new Facade();  
    61.     f2.MethodB();  
    62.       
    63.     Console.ReadLine();  
    64. }   


    策略模式 Strategy

           策略模式定义一系列的算法,把它们一个个封装起来,并且使它们可以相互替换。本模式使得算法的变化不会影响到使用算法的客户。

           策略模式将每一个算法封装到一个具有公共接口的独立类中,解除了客户与具体算法的直接耦合,是客户改变算法更为容易。

            策略模式+简单工厂+反射+配置文件可以组成更为灵活的方式。 


    1. /// <summary>    
    2. /// 算法的公共接口  
    3. /// </summary>   
    4. abstract public class Strategy{  
    5.     public abstract void AlgorithmInterface();  
    6. }  
    7.   
    8. /// <summary>    
    9. /// 具体算法A  
    10. /// </summary>   
    11. public class ConcreteStrategyA:Strategy{  
    12.     public override void AlgorithmInterface(){  
    13.         Console.Write("具体算法A");  
    14.     }  
    15. }  
    16.   
    17. /// <summary>    
    18. /// 具体算法B  
    19. /// </summary>   
    20. public class ConcreteStrategyB:Strategy{  
    21.     public override void AlgorithmInterface(){  
    22.         Console.Write("具体算法B");  
    23.     }  
    24. }  
    25.   
    26. /// <summary>    
    27. /// 具体算法C  
    28. /// </summary>   
    29. public class ConcreteStrategyC:Strategy{  
    30.     public override void AlgorithmInterface(){  
    31.         Console.Write("具体算法C");  
    32.     }  
    33. }  
    34.   
    35. /// <summary>    
    36. /// 上下文,用来维护一个对Strategy对象的引用。  
    37. /// </summary>   
    38. public class Context{  
    39.     private Strategy strategy;  
    40.       
    41.     public Context(Strategy strategy){  
    42.         this.strategy=strategy;  
    43.     }  
    44.       
    45.     //上下文接口  
    46.     public void ContextInterface(){  
    47.         strategy.AlgorithmInterface();  
    48.     }  
    49. }  
    50.   
    51. //client端  
    52. static void Main(string[] args)  
    53. {  
    54.     Context context = new Context(new ConcreteStrategyA());  
    55.     context.ContextInterface();  
    56.       
    57.     context = new Context(new ConcreteStrategyB());  
    58.     context.ContextInterface();  
    59.       
    60.     context = new Context(new ConcreteStrategyC());  
    61.     context.ContextInterface();  
    62.       
    63.     Console.ReadLine();  
    64. }   


    观察者模式 Observer

           观察者模式定义了对象间的一种一对多的依赖关系,当一个对象的状态发生变化时,所有依赖它的对象都会得到通知,并被自动更新,

             系统中有两个方面,其中一个方面依赖与另一个方面,我们把这两个方面抽象,是各自可以独立的变化和复用。

             就像我们现在所用到的分层,不就是一层层的依赖么?还有系统组件升级,系统功能也跟着变化,这也属于观察者模式。

      1. /// <summary>    
      2. /// 抽象观察类  
      3. /// </summary>   
      4. abstract public class Observer{  
      5.     public abstract void Update();  
      6. }  
      7.   
      8. /// <summary>    
      9. /// 具体观察类  
      10. /// </summary>   
      11. public class Concreteobserver:Observer{  
      12.     private string name;  
      13.     private string observerState;  
      14.     private ConcreteSubject subject;  
      15.       
      16.     public Concreteobserver(ConcreteSubject subject,string name){  
      17.         this.subject=subject;  
      18.         this.name= name;  
      19.     }  
      20.       
      21.     public override void Update(){  
      22.         observerState=subject.GetState();  
      23.         Console.write("观察者{0}的新状态是{1}",name,observerState);  
      24.     }  
      25. }  
      26.   
      27. /// <summary>    
      28. /// 抽象主题类  
      29. /// </summary>   
      30. abstract public class Subject(){  
      31.     private List<observer> observers = new List<observer>() ;  
      32.       
      33.     public void  Attach(Observer observer){  
      34.         observers.Add(Observer);  
      35.     }  
      36.       
      37.     public void Detach(Observer Observer){  
      38.         observers.Remove(Observer);  
      39.     }  
      40.       
      41.     public void NotifyObservers(){  
      42.         foreach(Observer o in observers){  
      43.             o.Update();  
      44.         }  
      45.     }  
      46. }  
      47.   
      48. /// <summary>    
      49. /// 具体主题类  
      50. /// </summary>   
      51. public class ConcreteSubject:Subject{  
      52.     private string subjectState;  
      53.       
      54.     public string SubjectState{  
      55.         get{return subjectstate;}  
      56.         set{subjectstrate=value;}  
      57.     }  
      58.       
      59.     public void GetState(){  
      60.         return subjectstate;  
      61.     }  
      62. }  
      63.   
      64. //client端  
      65. static void Main(string[] args)    
      66. {    
      67.     ConcreteSubject c = new ConcreteSubject();  
      68.     Concreteobserver o1 = new Concreteobserver(c,"X");  
      69.     Concreteobserver o2 = new Concreteobserver(c,"Y");  
      70.     Concreteobserver o3 = new Concreteobserver((c,"Z");  
      71.     c.Attach(o1);  
      72.     c.Attach(o2);  
      73.     c.Attach(o3);  
      74.     c.subjectstate="abc";  
      75.     c.Nofify();  
      76.       
      77.     Console.ReadLine();  
      78. }  
  • 相关阅读:
    Nginx 的 Location 配置指令块
    linux java环境配置
    WebUploader API文档
    cron表达式详解
    Android中设置自己软件的铃声+震动
    java格式化输出 printf 例子
    Android_Intent意图详解
    MyEclipse Could not create the view: An unexpected exception was thrown解决方案
    HttpClient技术
    java-Object类中的方法
  • 原文地址:https://www.cnblogs.com/sdya/p/5265122.html
Copyright © 2011-2022 走看看