Java中的23种设计模式

来源:互联网 发布:centos 7修改密码 编辑:程序博客网 时间:2024/06/06 17:00

Java中的23种设计模式:

Factory(工厂模式),      Builder(建造模式),       Factory Method(工厂方法模式),
Prototype(原始模型模式),Singleton(单例模式),    Facade(门面模式),
Adapter(适配器模式),    Bridge(桥梁模式),        Composite(合成模式),
Decorator(装饰模式),    Flyweight(享元模式),     Proxy(代理模式),
Command(命令模式),      Interpreter(解释器模式), Visitor(访问者模式),
Iterator(迭代子模式),   Mediator(调停者模式),    Memento(备忘录模式),
Observer(观察者模式),   State(状态模式),         Strategy(策略模式),

Template Method(模板方法模式), Chain Of Responsibleity(责任链模式)

  【IT168 技术】通常,一个设计模式描述了一个被证实可行的方案。这些方案非常普遍,是具有完整定义的最常用的模式。一般模式有4个基本要素:模式名称(pattern name)、问题(problem)、解决方案(solution)、效果(consequences)。

  常见的Java设计模式有以下23种:

  1、抽象工厂模式(Abstract Factory):

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

  2、适配器模式(Adapter):

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

  3、桥梁模式(Bridge):

  将抽象部分与它的实现部分分离,使它们都可以独立地变化。

  4、建造模式(Builder):

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

  5、责任链模式(Chain of Responsibility):

  为解除请求的发送者和接收者之间耦合,而使多个对象都有机会处理这个请求。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它。

  6、命令模式(Command):

  将一个请求封装为一个对象,从而可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可取消的操作。

  7、合成模式(Composite):

  将对象组合成树形结构以表示“部分-整体”的层次结构。它使得客户对单个对象和复合对象的使用具有一致性。

  8、装饰模式(Decorator):

  动态地给一个对象添加一些额外的职责。就扩展功能而言,它能生成子类的方式更为灵活。

  9、门面模式(Facade):

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

  10、工厂方法(Factory Method):

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

  11、享元模式(Flyweight):

  运用共享技术以有效地支持大量细粒度的对象。

  12、解释器模式(Interpreter):

  给定一个语言,定义它的语法的一种表示,并定义一个解释器,该解释器使用该表示解释语言中的句子。

  13、迭代子模式(Iterator):

  提供一种方法顺序访问一个聚合对象中的各个元素,而又不需暴露该对象的内部表示。

  14、调停者模式(Mediator):

  用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式的内部表示。

  15、备忘录模式(Memento):

  在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到保存的状态。

  16、观察者模式(Observer):

  定义对象间的一种一对多的依赖关系,以便当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并自动刷新。

  17、原始模型模式(Prototype):

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

  18、代理模式(Proxy):

  为其他对象提供一个代理以控制对这个对象的访问。

  19、单例模式(Singleton):

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

  20、状态模式(State):

  允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它所属的类。

  21、策略模式(Strategy):

  定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。本模式使得算法的变化可独立于使用它的客户。

  22、模板模式(Template Method):

  定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。

  23、访问者模式(Visitor):

  表示一个作用于某对象结构中的各元素的操作。该模式可以实现在不改变各元素的类的前提下定义作用于这些元素的新操作。

代码如下:

[java] view plaincopy
  1. package lq.test;  
  2.   
  3. import java.io.*;  
  4. import java.util.*;  
  5.   
  6. //*********创建型模式***************  
  7.   
  8. //factory method 1  
  9. //1具体的构造算法,和2构造出的具体产品由子类实现    
  10. interface Product {  
  11. }  
  12.   
  13. //或者我也提供一个工厂的接口,由这个抽象类来继承它  
  14.   
  15. abstract class Factory {  
  16.     abstract public Product fmd();;  
  17.       
  18.     //我认为这个方方法的存在是,是对FactoryMethod方法的补充  
  19.     //例如可以为生成的对象赋值,计算为生成对象应付何值,前后的日值  
  20.     //且这些都是公用的,生成产品的最主要算法还是在FactoryMethod中,  
  21.     //这个方法只是起辅助作用,这也是一种思维方法,将具体的算法实现在一个方法中  
  22.     //而我不直接调用此方法,而使用另外的一个方法封装它,等到了更灵活的效果,而  
  23.     //子类需实现的内容是FactoryMethod  
  24.     //此方法是一个TemplateMethod  
  25.     public Product creat(); {  
  26.         Product pd = null;  
  27.           
  28.         System.out.println("before operation");;  
  29.           
  30.         pd = fmd();;  
  31.           
  32.         System.out.println("end operation");;  
  33.       
  34.         return pd;  
  35.     }  
  36. }  
  37.   
  38. class Product1 implements Product {  
  39. }  
  40.   
  41. class Factory1 extends Factory {  
  42.     public Product fmd(); {  
  43.         Product pd = new Product1();;  
  44.         return pd;  
  45.     }  
  46. }  
  47.   
  48. //FactroyMethod 2  
  49. //这种方式简单实用  
  50. interface Producta {  
  51. }  
  52.   
  53. interface Factorya {  
  54.     Producta create();;  
  55. }  
  56.   
  57. class Producta1 implements Producta {}  
  58.   
  59. class Factorya1 implements Factorya {  
  60.     public Producta create(); {  
  61.         Producta pda = null;  
  62.         pda = new Producta1();;  
  63.         return pda;  
  64.     }   
  65. }  
  66.   
  67. //AbstractFactory  
  68. //AbstractFactory与FactoryMethod的不同在于AbstractFactory创建多个产品  
  69. //感觉此模式没有什么大用  
  70.   
  71. //当然可以还有更多的接口  
  72. interface Apda {}  
  73.   
  74. interface Apdb {}  
  75.   
  76. interface Afactory {  
  77.     Apda createA();;  
  78.     Apdb createB();;  
  79. }  
  80.   
  81. class Apda1 implements Apda {}  
  82.   
  83. class Apdb1 implements Apdb {}  
  84.   
  85. //有几个接口就有几个对应的方法  
  86. class Afactory1 implements Afactory {  
  87.     public Apda createA(); {  
  88.         Apda apda = null;  
  89.         apda = new Apda1();;  
  90.         return apda;  
  91.     }  
  92.       
  93.     public Apdb createB(); {  
  94.         Apdb apdb = null;  
  95.         apdb = new Apdb1();;  
  96.         return apdb;          
  97.     }  
  98. }  
  99.   
  100. //Builder  
  101. //一个产品的生成分为生成部件和组装部件,不同的产品每个部件生成的方式不同  
  102. //而组装的方式相同,部件的生成抽象成接口方法,而组装的方法使用一个TemplateMethod方法  
  103.   
  104. interface Cpda {}  
  105.   
  106. class Cpda1 implements Cpda {}  
  107.   
  108. interface BuilderI {  
  109.     void buildPart1();;  
  110.     void buildPart2();;  
  111.       
  112.     void initPd();;  
  113.     Cpda getPd();;  
  114. }  
  115.   
  116. abstract class BuilderA implements BuilderI {  
  117.     Cpda cpda;  
  118.       
  119.     public Cpda getPd(); {  
  120.         initPd();;  
  121.           
  122.         //对对象的内容进行设置  
  123.         buildPart1();;  
  124.         buildPart2();;  
  125.           
  126.         return cpda;  
  127.     }  
  128. }  
  129.   
  130. class Builder extends BuilderA {  
  131.     public void buildPart1(); {  
  132.         System.out.println(cpda);;  
  133.     }  
  134.       
  135.     public void buildPart2(); {  
  136.         System.out.println(cpda);;  
  137.     }  
  138.       
  139.     public void initPd(); {  
  140.         cpda = new Cpda1();;  
  141.     }     
  142. }  
  143.   
  144. //一个简单的生成产品的实现  
  145. //1  
  146. abstract class Fy {  
  147.     public abstract void med1();;   
  148.       
  149.     static class Fy1 extends Fy {  
  150.         public void med1(); {  
  151.         }  
  152.     }  
  153.       
  154.     public static Fy getInstance(); {  
  155.         Fy fy = new Fy1();;  
  156.         return fy;  
  157.           
  158. //      Fy fy = new Fy1(); {//这种匿名内部类是静态的!!  
  159. //          public void med1(); {  
  160. //          }  
  161. //      };        
  162. //      return fy;  
  163.     }  
  164. }  
  165.   
  166. //2  
  167. interface Pdd {}  
  168.   
  169. class Pdd1 implements Pdd {}  
  170.   
  171. abstract class Fya {  
  172.     public static Pdd getPd(); {  
  173.         Pdd pdd = new Pdd1();;  
  174.         return pdd;  
  175.     }  
  176. }  
  177.   
  178. //Prototype 在java中就是clone,又包含深拷贝和浅拷贝  
  179. class CloneObja {  
  180.     public CloneObja MyClone(); {  
  181.         return new CloneObja();;  
  182.     }  
  183. }  
  184.   
  185. class CloneObjb {  
  186.     public CloneObjb MyClone(); throws Throwable {  
  187.         CloneObjb cobj = null;  
  188.         cobj = (CloneObjb); pcl(this);;  
  189.         return cobj;  
  190.     }     
  191.       
  192.     //深度拷贝算法  
  193.     private Object pcl(Object obj); throws Throwable {  
  194.         ByteArrayOutputStream bao = new ByteArrayOutputStream(1000);;  
  195.         ObjectOutputStream objo = new ObjectOutputStream(bao);;  
  196.         objo.writeObject(obj);;  
  197.           
  198.         ByteArrayInputStream bai = new ByteArrayInputStream(bao.toByteArray(););;  
  199.         ObjectInputStream obji = new ObjectInputStream(bai);;  
  200.           
  201.         Object objr = obji.readObject();;  
  202.         return objr;  
  203.     }   
  204. }  
  205.   
  206. //Singleton  
  207. //一个类只有一个对象,例如一个线程池,一个cache  
  208. class Singleton1 {  
  209.     public static Singleton1 instance = new Singleton1();;    
  210.       
  211.     private Singleton1(); {       
  212.     }  
  213.       
  214.     public static Singleton1 getInstance(); {  
  215.         return instance;  
  216.     }  
  217. }  
  218.   
  219. class Singleton2 {  
  220.     public static Singleton2 instance;  
  221.       
  222.     private Singleton2(); {  
  223.     }  
  224.       
  225. //  public static Singleton2 getInstance(); {         
  226. //      if (instance == null); {  
  227. //          instance = new Singleton2();;  
  228. //      }  
  229. //        
  230. //      return instance;  
  231. //  }  
  232.       
  233.     public static Singleton2 getInstance(); {  
  234.         synchronized(Singleton2.class); {  
  235.             if (instance == null); {  
  236.                 instance = new Singleton2();;  
  237.             }  
  238.         }  
  239.           
  240.         return instance;  
  241.     }  
  242. }  
  243.   
  244. //**********结构型模式**********  
  245.   
  246. //Adapter  
  247. //基本方法有两种,一种是使用引用一种使用继承  
  248. //将不符合标准的接口转成符合标准的接口,接口的修改主要是参数的增减,  
  249. //返回值类型,当然还有方法名  
  250. //感觉这就是封装的另一种表示形式,封装有用方法封装(在方法中调用功能方法);,  
  251. //用类封装(先传入功能方法所在的类的对象,通过调用此对象的功能方法);  
  252.   
  253. //使用引用的形式  
  254. class Adapteea {  
  255.     public void kk(); {}  
  256. }  
  257.   
  258. interface Targeta {  
  259.     String vv(int i, int k);;  
  260. }  
  261.   
  262. class Adaptera implements Targeta{  
  263.     Adapteea ade;  
  264.       
  265.     public Adaptera(Adapteea ade); {  
  266.         this.ade = ade;  
  267.     }  
  268.       
  269.     public String vv(int i, int k); {  
  270.         //具体的业务方法实现在Adaptee中,这个方法  
  271.         //只起到了接口转换的作用  
  272.         //调用此方法是通过引用  
  273.         ade.kk();;  
  274.         return null;  
  275.     }  
  276. }  
  277.   
  278. //使用继承形式的  
  279. class Adapteeb {  
  280.     public void kk(); {}  
  281. }  
  282.   
  283. interface Targetb {  
  284.     String vv(int i, int k);;  
  285. }  
  286.   
  287. class Adapterb extends Adapteeb implements Targetb {  
  288.     public String vv(int i, int k); {  
  289.         //调用此方法是通过继承  
  290.         kk();;  
  291.         return null;  
  292.     }  
  293. }  
  294.   
  295. //Proxy  
  296. interface Subject {  
  297.     void request();;  
  298. }   
  299.   
  300. class realSubject implements Subject {  
  301.     public void request(); {          
  302.         //do the real business  
  303.     }  
  304. }  
  305.   
  306. class Proxy implements Subject {  
  307.     Subject subject;  
  308.       
  309.     public Proxy(Subject subject); {  
  310.         this.subject = subject;  
  311.     }  
  312.       
  313.     public void request(); {  
  314.         System.out.println("do something");;  
  315.           
  316.         subject.request();;  
  317.           
  318.         System.out.println("do something");;  
  319.     }  
  320. }  
  321.   
  322. //Bridge  
  323. //感觉就是多态的实现  
  324.   
  325. interface Imp {  
  326.     void operation();;  
  327. }  
  328.   
  329. class Cimp1 implements Imp {  
  330.     public void operation(); {  
  331.         System.out.println("1");;  
  332.     }  
  333. }  
  334.   
  335. class Cimp2 implements Imp {  
  336.     public void operation(); {  
  337.         System.out.println("2");;  
  338.     }  
  339. }  
  340.   
  341. class Invoker {  
  342.     Imp imp = new Cimp1();;  
  343.       
  344.     public void invoke(); {  
  345.         imp.operation();;  
  346.     }  
  347. }  
  348.   
  349. //Composite  
  350.   
  351. interface Component {  
  352.     void operation();;  
  353.       
  354.     void add(Component component);;  
  355.       
  356.     void remove(Component component);;  
  357. }  
  358.   
  359. class Leaf implements Component {  
  360.     public void operation(); {  
  361.         System.out.println("an operation");;  
  362.     }  
  363.       
  364.     public void add(Component component); {  
  365.         throw new UnsupportedOperationException();;  
  366.     }  
  367.       
  368.     public void remove(Component component); {  
  369.         throw new UnsupportedOperationException();;  
  370.     }  
  371. }  
  372.   
  373. class Composite implements Component {  
  374.     List components = new ArrayList();;  
  375.       
  376.     public void operation(); {  
  377.         Component component = null;  
  378.           
  379.         Iterator it = components.iterator();;         
  380.         while (it.hasNext();); {  
  381.             //不知道此component对象是leaf还是composite,  
  382.             //如果是leaf则直接实现操作,如果是composite则继续递归调用  
  383.             component = (Component); it.next();;  
  384.             component.operation();;  
  385.         }  
  386.     }  
  387.       
  388.     public void add(Component component); {       
  389.         components.add(component);;  
  390.     }  
  391.       
  392.     public void remove(Component component); {        
  393.         components.remove(component);;  
  394.     }  
  395. }  
  396.   
  397. //Decorator  
  398. //对一个类的功能进行扩展时,我可以使用继承,但是不够灵活,所以选用了  
  399. //另外的一种形式,引用与继承都可活得对对象的一定的使用能力,而使用引用将更灵活  
  400. //我们要保证是对原功能的追加而不是修改,否则只能重写方法,或使用新的方法  
  401. //注意concrete的可以直接new出来,  
  402. //而decorator的则需要用一个另外的decorator对象才能生成对象  
  403. //使用对象封装,和公用接口  
  404. //Decorator链上可以有多个元素  
  405.   
  406. interface Componenta {  
  407.     void operation();;  
  408. }  
  409.   
  410. class ConcreteComponent implements Componenta {  
  411.     public void operation(); {  
  412.         System.out.println("do something");;  
  413.     }  
  414. }  
  415.   
  416. class Decorator implements Componenta {  
  417.     private Componenta component;  
  418.       
  419.     public Decorator(Componenta component); {  
  420.         this.component = component;  
  421.     }  
  422.       
  423.     public void operation(); {  
  424.         //do something before  
  425.           
  426.         component.operation();;  
  427.           
  428.         //do something after  
  429.     }  
  430. }  
  431.   
  432. //Facade  
  433. //非常实用的一种设计模式,我可以为外部提供感兴趣的接口  
  434.   
  435. class Obj1 {  
  436.     public void ope1(); {}  
  437.     public void ope2(); {}  
  438. }  
  439.   
  440. class Obj2 {  
  441.     public void ope1(); {}  
  442.     public void ope2(); {}  
  443. }  
  444.   
  445. class Facade {  
  446.     //我得到了一个简洁清晰的接口  
  447.     public void fdMethod(); {  
  448.         Obj1 obj1 = new Obj1();;  
  449.         Obj2 obj2 = new Obj2();;  
  450.           
  451.         obj1.ope1();;  
  452.         obj2.ope2();;  
  453.     }  
  454. }  
  455.   
  456. //Flyweight  
  457. //空  
  458.   
  459. //**********行为型模式*************  
  460.   
  461. //Chain of Responsibility  
  462. //与Decorator的实现形式相类似,  
  463. //Decorator是在原来的方法之上进行添加功能,而  
  464. //Chain则是判断信号如果不是当前处理的则转交个下一个节点处理  
  465. //我可以使用if分支来实现相同的效果,但是不够灵活,链上的每个节点是可以替换增加的,相对  
  466. //比较灵活,我们可以设计接口实现对节点的增删操作,而实现更方便的效果  
  467. //这个是一个链状的结构,有没有想过使用环状结构  
  468.   
  469. interface Handler {  
  470.     void handRequest(int signal);;  
  471. }  
  472.   
  473. class CHandler1 implements Handler {  
  474.     private Handler handler;  
  475.       
  476.     public CHandler1(Handler handler); {  
  477.         this.handler = handler;  
  478.     }  
  479.       
  480.     public void handRequest(int signal); {  
  481.         if (signal == 1); {  
  482.             System.out.println("handle signal 1");;  
  483.         }  
  484.         else {  
  485.             handler.handRequest(signal);;  
  486.         }  
  487.     }   
  488. }  
  489.   
  490. class CHandler2 implements Handler {  
  491.     private Handler handler;  
  492.       
  493.     public CHandler2(Handler handler); {  
  494.         this.handler = handler;  
  495.     }  
  496.       
  497.     public void handRequest(int signal); {  
  498.         if (signal == 2); {  
  499.             System.out.println("handle signal 2");;  
  500.         }  
  501.         else {  
  502.             handler.handRequest(signal);;  
  503.         }  
  504.     }   
  505. }  
  506.   
  507. class CHandler3 implements Handler {  
  508.     public void handRequest(int signal); {  
  509.         if (signal == 3); {  
  510.             System.out.println("handle signal 3");;  
  511.         }  
  512.         else {  
  513.             throw new Error("can't handle signal");;  
  514.         }  
  515.     }   
  516. }  
  517.   
  518. class ChainClient {  
  519.     public static void main(String[] args); {  
  520.         Handler h3 = new CHandler3();;  
  521.         Handler h2 = new CHandler2(h3);;  
  522.         Handler h1 = new CHandler1(h2);;  
  523.           
  524.         h1.handRequest(2);;  
  525.     }  
  526. }  
  527.   
  528. //Interpreter  
  529. //感觉跟Composite很类似,只不过他分文终结符和非终结符  
  530.   
  531. //Template Method  
  532.   
  533. abstract class TemplateMethod {  
  534.     abstract void amd1();;  
  535.       
  536.     abstract void amd2();;  
  537.       
  538.     //此方法为一个Template Method方法  
  539.     public void tmd(); {  
  540.         amd1();;  
  541.         amd2();;  
  542.     }  
  543. }  
  544.   
  545. //State  
  546.   
  547. //标准型  
  548. //状态和操作不应该耦合在一起  
  549. class Contexta {  
  550.     private State st;  
  551.       
  552.     public Contexta(int nst); {  
  553.         changeStfromNum(nst);;  
  554.     }  
  555.       
  556.     public void changeStfromNum(int nst); {  
  557.         if (nst == 1); {  
  558.             st = new CStatea1();;  
  559.         }  
  560.         else if (nst == 2); {  
  561.             st = new CStatea2();;  
  562.         }  
  563.           
  564.         throw new Error("bad state");;  
  565.     }  
  566.       
  567.     void request(); {  
  568.         st.handle(this);;  
  569.     }  
  570. }  
  571.   
  572. interface State {  
  573.     void handle(Contexta context);;  
  574. }  
  575.   
  576. class CStatea1 implements State {  
  577.     public void handle(Contexta context); {  
  578.         System.out.println("state 1");;  
  579.         //也许在一个状态的处理过程中要改变状态,例如打开之后立即关闭这种效果  
  580.         //context.changeStfromNum(2);;  
  581.     }  
  582. }  
  583.   
  584. class CStatea2 implements State {  
  585.     public void handle(Contexta context); {  
  586.         System.out.println("state 2");;  
  587.     }  
  588. }  
  589.   
  590. //工厂型  
  591. //根据状态不通生成不同的state  
  592.   
  593. //class StateFactory {  
  594. //  public static State getStateInstance(int num); {  
  595. //      State st = null;  
  596. //        
  597. //      if (num == 1); {  
  598. //          st = new CStatea1();;  
  599. //      }  
  600. //      else if (num == 2); {  
  601. //          st = new CStatea2();;  
  602. //      }  
  603. //        
  604. //      return st;  
  605. //  }  
  606. //}  
  607.   
  608. //Strategy  
  609. //跟Bridge相类似,就是一种多态的表示  
  610.   
  611. //Visitor  
  612. //双向引用,使用另外的一个类调用自己的方法,访问自己的数据结构  
  613. interface Visitor {   
  614.     void visitElement(Elementd element);;  
  615. }  
  616.   
  617. class CVisitor implements Visitor {  
  618.     public void visitElement(Elementd element); {  
  619.         element.operation();;  
  620.     }  
  621. }  
  622.   
  623. interface Elementd {      
  624.     void accept(Visitor visitor);;  
  625.       
  626.     void operation();;  
  627. }  
  628.   
  629. class CElementd implements Elementd {  
  630.     public void accept(Visitor visitor); {  
  631.         visitor.visitElement(this);;  
  632.     }  
  633.       
  634.     public void operation(); {  
  635.         //实际的操作在这里  
  636.     }  
  637. }  
  638.   
  639. class Clientd {  
  640.     public static void main(); {  
  641.         Elementd elm = new CElementd();;  
  642.         Visitor vis = new CVisitor();;  
  643.           
  644.         vis.visitElement(elm);;  
  645.     }  
  646. }  
  647.   
  648. //Iteraotr  
  649. //使用迭代器对一个类的数据结构进行顺序迭代  
  650.   
  651. interface Structure {  
  652.     interface Iteratora {  
  653.         void first();;  
  654.           
  655.         boolean hasElement();;  
  656.           
  657.         Object next();;  
  658.           
  659.     }  
  660. }  
  661.   
  662. class Structure1 implements Structure {  
  663.     Object[] objs = new Object[100];  
  664.       
  665.     //使用内部类是为了对Struture1的数据结构有完全的访问权  
  666.     class Iteratora1 implements Iteratora {  
  667.         int index = 0;  
  668.           
  669.         public void first(); {  
  670.             index = 0;  
  671.         }  
  672.           
  673.         public boolean hasElement(); {  
  674.             return index < 100;  
  675.         }   
  676.           
  677.         public Object next(); {  
  678.             Object obj = null;  
  679.               
  680.             if (hasElement();); {  
  681.                 obj = objs[index];  
  682.                 index++;  
  683.             }  
  684.               
  685.             return obj;  
  686.         }  
  687.     }  
  688. }  
  689.   
  690. //Meditor  
  691.   
  692. class A1 {  
  693.     public void operation1(); {}  
  694.     public void operation2(); {}  
  695. }  
  696.   
  697. class A2 {  
  698.     public void operation1(); {}  
  699.     public void operation2(); {}  
  700. }  
  701.   
  702. class Mediator {  
  703.     A1 a1;  
  704.     A2 a2;  
  705.       
  706.     public Mediator(A1 a1, A2 a2); {  
  707.         this.a1 = a1;  
  708.         this.a2 = a2;  
  709.           
  710.     }  
  711.       
  712.     //如果我想实现这个功能我可能会把他放在A1中  
  713.     //但是这样耦合大,我不想在A1中出现A2对象的引用,  
  714.     //所以我使用了Mediator作为中介  
  715.     public void mmed1(); {  
  716.         a1.operation1();;  
  717.         a2.operation2();;  
  718.     }  
  719.       
  720.     public void mmed2(); {  
  721.         a2.operation1();;  
  722.         a1.operation2();;  
  723.     }  
  724. }  
  725.   
  726. //Command  
  727. //我认为就是将方法转换成了类  
  728.   
  729. class Receiver {  
  730.     public void action1(); {}  
  731.       
  732.     public void action2(); {}  
  733. }  
  734.   
  735. interface Command {  
  736.     void Execute();;  
  737. }  
  738.   
  739. class CCommand1 implements Command {  
  740.     private Receiver receiver;  
  741.       
  742.     public CCommand1(Receiver receiver); {  
  743.         this.receiver = receiver;  
  744.     }  
  745.       
  746.     public void Execute(); {  
  747.         receiver.action1();;  
  748.     }  
  749. }  
  750.   
  751. class CCommand2 implements Command {  
  752.     private Receiver receiver;  
  753.       
  754.     public CCommand2(Receiver receiver); {  
  755.         this.receiver = receiver;  
  756.     }  
  757.       
  758.     public void Execute(); {  
  759.         receiver.action2();;  
  760.     }  
  761. }  
  762.   
  763. //Observer  
  764. //在这里看似乎这个模式没有什么用  
  765. //但是如果我有一个线程监控Subject,如果Subject的状态  
  766. //发生了变化,则更改Observer的状态,并出发一些操作,这样就有实际的意义了  
  767. //Observer与Visitor有相似的地方,都存在双向引用  
  768. //Subject可以注册很多Observer  
  769.   
  770. interface Subjectb {  
  771.     void attach(Observer observer);;  
  772.       
  773.     void detach(Observer observer);;  
  774.       
  775.     void mynotify();;  
  776.       
  777.     int getState();;  
  778.       
  779.     void setState(int state);;  
  780. }  
  781.   
  782. class Subjectb1 implements Subjectb {  
  783.     List observers = new ArrayList();;  
  784.     int state;  
  785.       
  786.     public void attach(Observer observer); {  
  787.         observers.add(observer);;  
  788.     }  
  789.       
  790.     public void detach(Observer observer); {  
  791.         observers.remove(observer);;  
  792.     }  
  793.       
  794.     public void mynotify(); {  
  795.         Observer observer = null;  
  796.         Iterator it = observers.iterator();;  
  797.           
  798.         while (it.hasNext();); {  
  799.             observer = (Observer); it.next();;  
  800.             observer.Update();;  
  801.         }  
  802.     }  
  803.   
  804.     public int getState(); {  
  805.         return state;  
  806.     }  
  807.   
  808.     public void setState(int state); {  
  809.         this.state = state;  
  810.     }  
  811. }  
  812.   
  813. interface Observer {  
  814.     void Update();;  
  815. }  
  816.   
  817. class Observer1 implements Observer {  
  818.     Subjectb subject;  
  819.     int state;  
  820.       
  821.     public Observer1(Subjectb subject); {  
  822.         this.subject = subject;  
  823.     }  
  824.       
  825.     public void Update(); {       
  826.         this.state = subject.getState();;  
  827.     }  
  828.       
  829.     public void operation(); {  
  830.         //一些基于state的操作  
  831.     }  
  832. }  
  833.   
  834. //Memento  
  835. //感觉此模式没有什么大用  
  836.   
  837. class Memento {  
  838.     int state;  
  839.   
  840.     public int getState(); {  
  841.         return state;  
  842.     }  
  843.   
  844.     public void setState(int state); {  
  845.         this.state = state;  
  846.     }  
  847. }  
  848.   
  849. class Originator {  
  850.     int state;  
  851.       
  852.     public void setMemento(Memento memento); {  
  853.         state = memento.getState();;  
  854.     }  
  855.       
  856.     public Memento createMemento(); {  
  857.         Memento memento = new Memento();;  
  858.         memento.setState(1);;  
  859.         return memento;  
  860.     }  
  861.   
  862.     public int getState(); {  
  863.         return state;  
  864.     }  
  865.   
  866.     public void setState(int state); {  
  867.         this.state = state;  
  868.     }  
  869. }  
  870.   
  871. class careTaker {  
  872.     Memento memento;  
  873.       
  874.     public void saverMemento(Memento memento); {  
  875.         this.memento = memento;  
  876.     }  
  877.       
  878.     public Memento retrieveMemento(); {  
  879.         return memento;  
  880.     }  
  881. }  
  882.   
  883. //程序最终还是顺序执行的,是由不通部分的操作拼接起来的  
  884. //将不同类的代码拼接起来是通过引用实现的,有了引用我就  
  885. //相当于有了一定访问数据结构和方法的能力,这与写在类内部  
  886. //差不多,例如我想将一个类中的一个方法抽离出去,因为这个方法依赖与此类的数据和其他方法  
  887. //直接将代码移走是不行的,但如果我们拥有了此类对象的引用,则与写在此类  
  888. //内部无异,所以我们拥有了引用就可以将此方法移出  
  889. public class tt1 {  
  890.     public static void main(String[] args); {  
  891.     }  
  892. }  


常用的九种模式:

  1 Factory Pattern(工厂模式)

  上榜理由:将程序中创建对象的操作,单独出来处理,大大提高了系统扩展的柔性,接口的抽象化处理给相互依赖的对象创建提供了最好的抽象模式。

  2 Facade Pattern

  上榜理由:将表现层和逻辑层隔离,封装底层的复杂处理,为用户提供简单的接口,这样的例子随处可见。门面模式很多时候更是一种系统架构的设计,在我所做的项目中,就实现了门面模式的接口,为复杂系统的解耦提供了最好的解决方案。

  3 Command Pattern

  上榜理由:将请求封装为对象,从而将命令的执行和责任分开。通常在队列中等待命令,这和现实多么的相似呀。如果你喜欢发号施令,请考虑你的ICommond吧。

  4 Strategy Pattern

  上榜理由:策略模式,将易于变化的部分封装为接口,通常Strategy 封装一些运算法则,使之能互换。Bruce Zhang在他的博客中提到策略模式其实是一种“面向接口”的编程方法,真是恰如其分。

  5 Iterator Pattern

  上榜理由:相信任何的系统中,都会用到数组、集合、链表、队列这样的类型吧,那么你就不得不关心迭代模式的来龙去脉。在遍历算法中,迭代模式提供了遍历的顺序访问容器,GOF给出的定义为:提供一种方法访问一个容器(container)对象中各个元素,而又不需暴露该对象的内部细节。.NET中就是使用了迭代器来创建用于foreach的集合。

  6 Adapter Pattern

  上榜理由:在原类型不做任何改变的情况下,扩展了新的接口,灵活且多样的适配一切旧俗。这种打破旧框框,适配新格局的思想,是面向对象的精髓。以继承方式实现的类的Adapter模式和以聚合方式实现的对象的Adapter模式,各有千秋,各取所长。看来,把它叫做包装器一点也不为过,

  7 Observer Pattern

  上榜理由:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时, 所有依赖于它的对象都得到通知并被自动更新。观察者和被观察者的分开,为模块划分提供了清晰的界限。在.NET中使用委托和事件可以更好的实现观察者模式,事件的注册和撤销不就对应着观察者对其对象的观察吗?

  8 Bridge Pattern

  上榜理由:把实现和逻辑分开,对于我们深刻理解面向对象的聚合复用的思想甚有助益。

  9 Singleton Pattern(单例模式)

  上榜理由:改善全局变量和命名空间的冲突,可以说是一种改良了的全局变量。这种一个类只有一个实例,且提供一个访问全局点的方式,更加灵活的保证了实例的创建和访问约束。



原创粉丝点击