简介

设计模式可以分为五类

  1. 接口型 模式:适配器模式,外观模式,合成模式,桥接模式
  2. 职责型 模式:单例模式,观察者模式,调停者模式,代理模式,职责链模式,享元模式
  3. 构造型 模式:构建者模式,工厂方法模式,抽象工厂模式,原型模式,备忘录模式
  4. 操作型 模式:模板方法模式,状态模式,策略模式,命令模式,解析器模式
  5. 扩展型 模式:装饰器模式,迭代器模式,访问者模式。

 接口类

适配器模式 通过一个接口来适配类的接口

接口的优点:限制了类之间的协作 , 即使实现类发生巨大变化, 接口的客户端也不受影响

不同场景下使用 的模式

  1. 适配类的接口,以匹配客户端期待的接口-->适配器模式
  2. 为一组类提供简单接口-->外观模式
  3. 为简单对象和复合对象提供统一接口-->合成模式
  4. 解除抽象与实现之间的耦合,使得二者独立演化-->桥接模式

1. 适配器模式

 类适配器

使用继承方式,是静态的继承方式

简述 :接口中的方法  分别在父类和子类中实现

写一个demo

接口中有两个方法

  1. public interface Target {
  2.  
  3. void firstMethod();
  4.  
  5. void secondMethod();
  6. }

adaptee只有一个方法

  1. public class Adaptee {
  2. public void firstMethod(){
  3. System.out.println("this is first method.");
  4. }
  5. }

adapter 继承 adaptee 并实现 secondMethod

  1. public class Adapter extends Adaptee implements Target {
  2. @Override
  3. public void secondMethod() {
  4. System.out.println("this second method.");
  5. }
  6. }

  

对象适配器  

采用委派的方式

将  adaptee组合到 adpter2中

写个demo

  1. public class Adapter2 implements Target{
  2. private Adaptee adaptee;
  3.  
  4. public Adapter2(Adaptee adaptee) {
  5. this.adaptee = adaptee;
  6. }
  7.  
  8. @Override
  9. public void firstMethod() {
  10. this.adaptee.firstMethod();
  11. }
  12.  
  13. @Override
  14. public void secondMethod() {
  15. System.out.println("this second method.");
  16. }
  17. }

优点:代码复用,扩展 ,灵活 ,强大

缺点:是系统零乱 不易把握   

 2.外观模式

外观模式的意图是为 子系统 提供提供一个接口, 方便使用

外观类可能全是静态方法

简单描述一下  为复杂的子系统 提供一个 简单的调用门面

网上找了个易于理解的例子 http://www.aichengxu.com/java/681321.htm

一个人申请开公司 他需要分别 去 工商局,银行,公安局,质监局,税务部门 办理相关手续 特别麻烦

现在 有个绿色通道 ,actor只要 和它对接 既可以完成 上述操作  这个 绿色通道便可以看成是 一个 facade

这样看来  facade 模式 减少了客户端和 各个子系统之间交互,减少耦合。使接入变得简单

写一个简单的demo

工商系统

  1. public class Indutry {
  2. void regist(){
  3. System.out.println("indutry registration.");
  4. }
  5. }

公安系统

  1. public class PoliceStation {
  2. void regist(){
  3. System.out.println("police station registration.");
  4. }
  5. }

税务系统

  1. public class RevenueDepartment {
  2. void regist(){
  3. System.out.println("revenue department registration.");
  4. }
  5. }

facade

  1. public class Facade {
  2. public void buildCompany() {
  3. Indutry indutry = new Indutry();
  4. PoliceStation policeStation = new PoliceStation();
  5. RevenueDepartment revenueDepartment = new RevenueDepartment();
  6.  
  7. indutry.regist();
  8. policeStation.regist();
  9. revenueDepartment.regist();
  10. }
  11. }

3.合成模式

composite :组合对象 ,单对象 。组对象和单对象有共同的行为

组合对象 可以包括其他组合对象,也可以包括单对象。

合成模式 作用:保证客户端调用 单对象与组合对象的一致性

安全合成模式

管理聚集的方法 只出现在树枝构建中

写一个demo

相同接口

  1. public interface Component {
  2. void printStruct(String preStr);
  3. }

组合

  1. public class Composite implements Component {
  2. private List<Component> childComponens = new ArrayList<Component>();
  3. private String name;
  4.  
  5. public void add(Component child) {
  6. childComponens.add(child);
  7. }
  8.  
  9. public void remove(int index) {
  10. childComponens.remove(index);
  11. }
  12.  
  13. public Composite(String name) {
  14. this.name = name;
  15. }
  16.  
  17. public List<Component> getChildComponens() {
  18. return childComponens;
  19. }
  20.  
  21. public void setChildComponens(List<Component> childComponens) {
  22. this.childComponens = childComponens;
  23. }
  24.  
  25. public String getName() {
  26. return name;
  27. }
  28.  
  29. public void setName(String name) {
  30. this.name = name;
  31. }
  32.  
  33. @Override
  34. public void printStruct(String preStr) {
  35. System.out.println(preStr + "-->" + name);
  36. if (childComponens != null) {
  37. preStr += " ";
  38. for (Component child : childComponens) {
  39. //递归调用
  40. child.printStruct(preStr);
  41. }
  42. }
  43.  
  44. }
  45. }

叶子节点

  1. public class Leaf implements Component {
  2.  
  3. private String name;
  4.  
  5. public Leaf(String name) {
  6. this.name = name;
  7. }
  8.  
  9. public String getName() {
  10. return name;
  11. }
  12.  
  13. public void setName(String name) {
  14. this.name = name;
  15. }
  16. @Override
  17. public void printStruct(String preStr) {
  18. System.out.println(preStr+"-->"+name);
  19. }
  20. }

 测试

  1. public void test(){
  2. Composite root=new Composite("knowledge");
  3. //java 节点
  4. Composite java=new Composite("java");
  5.  
  6. Composite map=new Composite("Map");
  7. map.add(new Leaf("HashMap"));
  8. map.add(new Leaf("TreeMap"));
  9.  
  10. java.add(new Leaf("JVM"));
  11. java.add(new Leaf("List"));
  12. java.add(map);
  13.  
  14. //spring节点
  15. Composite spring=new Composite("spring");
  16. spring.add(new Leaf("AOP"));
  17. spring.add(new Leaf("IOC"));
  18.  
  19. // root add
  20. root.add(java);
  21. root.add(spring);
  22.  
  23. root.printStruct("");
  24. }

运行结果

 

  

4. 桥接模式

桥接模式 (bridge)关注抽象

桥接模式的意图  是  将 抽象与抽象方法的实现 相互分离出来, 实现 解耦合,以便二者可以相互独立

简单的说 就是 将对象 与方法分离

书上看到一个例子:现在有 2种设备 分别有  启动  关闭 2个抽象方法。

写个简单的 demo

抽象设备

  1. public abstract class AbstractMachine {
  2.  
  3. private MechineMethod mechineMethod;
  4.  
  5. public void setMechineMethod(MechineMethod mechineMethod) {
  6. this.mechineMethod = mechineMethod;
  7. }
  8.  
  9. public MechineMethod getMechineMethod() {
  10. return mechineMethod;
  11. }
  12.  
  13. abstract void checkMethod();
  14. }  

设备A

  1. public class MachineA extends AbstractMachine {
  2. @Override
  3. void checkMethod() {
  4. System.out.println("check machine A ......");
  5. }
  6. }

 

设备B

  1. public class MachineB extends AbstractMachine {
  2. @Override
  3. void checkMethod() {
  4. System.out.println("check machine B ......");
  5. }
  6. }

要检测的功能 的抽象类 (这里对方法的处理 将常规的 竖 转 横,方法平铺 )

  1. public abstract class MechineMethod {
  2. abstract void methodRun();
  3. }

  

start功能

  1. public class StartMethod extends MechineMethod {
  2. @Override
  3. void methodRun() {
  4. System.out.println("start method running.");
  5. }
  6. }

  

close功能

  1. public class CloseMethod extends MechineMethod {
  2. @Override
  3. void methodRun() {
  4. System.out.println("close method running.");
  5. }
  6. }

  

 

测试 检测 A设备的Start功能

  1. //检测A设备的 start功能
  2. public void test() {
  3. //检测A设备的 start功能
  4. AbstractMachine machine = new MachineA();
  5. MechineMethod mechineMethod = new StartMethod();
  6. machine.setMechineMethod(mechineMethod);
  7. machine.checkMethod();
  8. machine.getMechineMethod().methodRun();
  9. }

输出结果

 职责类 

 

 我们常见的职责模式 如

根据可见性控制职责 :java代码中的 public,private,protected

职责设计模式

  1. 将职责集中到某个类的单个实例中-->单例模式
  2. 将对象从依赖它的对象中解耦-->观察者模式
  3. 将职责集中在某个类,该类可以监督其他对象的交互-->调停者模式
  4. 让一个对象扮演其他对象的行为--代理模式
  5. 允许将职责链的请求传递给其他对象,直到这个请求被某个对象处理-->职责链模式
  6. 将共享的 细粒度的职责 进行集中管理-->享元模式

 

 1. 单例模式

单例模式 : 是确保一个类的 有且仅有一个实例,并为它提供一个全局访问点

单例模式中 往往使用 static关键字

static 修饰的变量为 静态变量,静态变量只在类第一次调用的时候加载 ,在内存中只有一个副本。

 

1.饿汉模式

  1. public class EagerSingleton {
  2. private static EagerSingleton eagerSingleton=new EagerSingleton();
  3.  
  4. private EagerSingleton() {
  5. }
  6.  
  7. public EagerSingleton getSingleton(){
  8. return eagerSingleton;
  9. }
  10. }

2.懒加载模式

  1. public class LazzySingleton {
  2. private static LazzySingleton lazzySingleton;
  3.  
  4. private LazzySingleton() {
  5. }
  6.  
  7. //同步方法
  8. public static synchronized LazzySingleton getSingleton() {
  9. if (lazzySingleton == null) {
  10. lazzySingleton = new LazzySingleton();
  11. }
  12. return lazzySingleton;
  13. }
  14. }

3.  支持多线程

  1. public class Singleton {
  2. private static Singleton singleton;
  3.  
  4. private Singleton() {
  5. }
  6.  
  7. public static Singleton getSingleton() {
  8. //先条件 后程序
  9. if (singleton == null) {
  10. //锁 住整个对象
  11. synchronized (Singleton.class) {
  12. singleton = new Singleton();
  13. }
  14. }
  15. return singleton;
  16. }
  17. }

  

2. 观察者模式

Observer  [əbˈzɜ:rvə(r)]

观察者模式:在多个对象之间定义一对多依赖关系,当一个对象的状态发生改变时,通知你依赖于它的对象,并根据新状态做出相应反应。

写一个demo

如 写一个 微博更新自动推送给客户

抽象 WeiBo 父类

  1. public abstract class WeiBo {
  2. //保存 Observer
  3. private List<Observer> list = new ArrayList<Observer>();
  4.  
  5. public void addObserver(Observer observer) {
  6. list.add(observer);
  7. }
  8.  
  9. public void delObserver(Observer observer) {
  10. list.remove(observer);
  11. }
  12.  
  13. //通知所有观察者
  14. public void notifyObservers(String operation) {
  15. for (Observer observer : list) {
  16. observer.update(operation);
  17. }
  18. }
  19. }

具体的Video类

  1. public class Video extends WeiBo {
  2. private String operation;
  3.  
  4. public String getOperation() {
  5. return operation;
  6. }
  7.  
  8. public void change(String operation) {
  9. this.operation = operation;
  10. notifyObservers(operation);
  11. }
  12. }

观察者接口

  1. public interface Observer {
  2. public void update(String operation);
  3. }

监听文件大小的观察者

  1. public class ObserverSize implements Observer {
  2. private String operation;
  3.  
  4. @Override
  5. public void update(String operation) {
  6. this.operation = operation;
  7. System.out.println("Observer Size : " + operation);
  8. }
  9. }

写一个测试的demo

  1. public void test() {
  2. Video video = new Video();
  3. Observer observer = new ObserverSize();
  4. video.addObserver(observer);
  5. video.change("compress video");//压缩视频
  6. }

运行结果

推模式 

主题发生改变时自动推送给观察者 ,不管观察者是否需要,主题推送的通常是主题对象的全部数据 或部分数据

拉模式

主题发生改变时 只传递少了信息给观察者  ,观察者根据需再向主题拉取数据。

java 提供的观察者支持类  

Observable

Observable [əbˈzərvəbəl] 可观察

被观察的类只要继承该类即可。

  

  1. public class Observable {
  2. private boolean changed = false;
  3. private Vector<Observer> obs;
  4.  
  5. /** Construct an Observable with zero Observers. */
  6.  
  7. public Observable() {
  8. obs = new Vector<>();
  9. }
  10.  
  11. /**
  12. * Adds an observer to the set of observers for this object, provided
  13. * that it is not the same as some observer already in the set.
  14. * The order in which notifications will be delivered to multiple
  15. * observers is not specified. See the class comment.
  16. *
  17. * @param o an observer to be added.
  18. * @throws NullPointerException if the parameter o is null.
  19. */
  20. public synchronized void addObserver(Observer o) {
  21. if (o == null)
  22. throw new NullPointerException();
  23. if (!obs.contains(o)) {
  24. obs.addElement(o);
  25. }
  26. }
  27.  
  28. /**
  29. * Deletes an observer from the set of observers of this object.
  30. * Passing <CODE>null</CODE> to this method will have no effect.
  31. * @param o the observer to be deleted.
  32. */
  33. public synchronized void deleteObserver(Observer o) {
  34. obs.removeElement(o);
  35. }
  36.  
  37. /**
  38. * If this object has changed, as indicated by the
  39. * <code>hasChanged</code> method, then notify all of its observers
  40. * and then call the <code>clearChanged</code> method to
  41. * indicate that this object has no longer changed.
  42. * <p>
  43. * Each observer has its <code>update</code> method called with two
  44. * arguments: this observable object and <code>null</code>. In other
  45. * words, this method is equivalent to:
  46. * <blockquote><tt>
  47. * notifyObservers(null)</tt></blockquote>
  48. *
  49. * @see java.util.Observable#clearChanged()
  50. * @see java.util.Observable#hasChanged()
  51. * @see java.util.Observer#update(java.util.Observable, java.lang.Object)
  52. */
  53. public void notifyObservers() {
  54. notifyObservers(null);
  55. }
  56.  
  57. /**
  58. * If this object has changed, as indicated by the
  59. * <code>hasChanged</code> method, then notify all of its observers
  60. * and then call the <code>clearChanged</code> method to indicate
  61. * that this object has no longer changed.
  62. * <p>
  63. * Each observer has its <code>update</code> method called with two
  64. * arguments: this observable object and the <code>arg</code> argument.
  65. *
  66. * @param arg any object.
  67. * @see java.util.Observable#clearChanged()
  68. * @see java.util.Observable#hasChanged()
  69. * @see java.util.Observer#update(java.util.Observable, java.lang.Object)
  70. */
  71. public void notifyObservers(Object arg) {
  72. /*
  73. * a temporary array buffer, used as a snapshot of the state of
  74. * current Observers.
  75. */
  76. Object[] arrLocal;
  77.  
  78. synchronized (this) {
  79. /* We don't want the Observer doing callbacks into
  80. * arbitrary code while holding its own Monitor.
  81. * The code where we extract each Observable from
  82. * the Vector and store the state of the Observer
  83. * needs synchronization, but notifying observers
  84. * does not (should not). The worst result of any
  85. * potential race-condition here is that:
  86. * 1) a newly-added Observer will miss a
  87. * notification in progress
  88. * 2) a recently unregistered Observer will be
  89. * wrongly notified when it doesn't care
  90. */
  91. if (!changed)
  92. return;
  93. arrLocal = obs.toArray();
  94. clearChanged();
  95. }
  96.  
  97. for (int i = arrLocal.length-1; i>=0; i--)
  98. ((Observer)arrLocal[i]).update(this, arg);
  99. }
  100.  
  101. /**
  102. * Clears the observer list so that this object no longer has any observers.
  103. */
  104. public synchronized void deleteObservers() {
  105. obs.removeAllElements();
  106. }
  107.  
  108. /**
  109. * Marks this <tt>Observable</tt> object as having been changed; the
  110. * <tt>hasChanged</tt> method will now return <tt>true</tt>.
  111. */
  112. protected synchronized void setChanged() {
  113. changed = true;
  114. }
  115.  
  116. /**
  117. * Indicates that this object has no longer changed, or that it has
  118. * already notified all of its observers of its most recent change,
  119. * so that the <tt>hasChanged</tt> method will now return <tt>false</tt>.
  120. * This method is called automatically by the
  121. * <code>notifyObservers</code> methods.
  122. *
  123. * @see java.util.Observable#notifyObservers()
  124. * @see java.util.Observable#notifyObservers(java.lang.Object)
  125. */
  126. protected synchronized void clearChanged() {
  127. changed = false;
  128. }
  129.  
  130. /**
  131. * Tests if this object has changed.
  132. *
  133. * @return <code>true</code> if and only if the <code>setChanged</code>
  134. * method has been called more recently than the
  135. * <code>clearChanged</code> method on this object;
  136. * <code>false</code> otherwise.
  137. * @see java.util.Observable#clearChanged()
  138. * @see java.util.Observable#setChanged()
  139. */
  140. public synchronized boolean hasChanged() {
  141. return changed;
  142. }
  143.  
  144. /**
  145. * Returns the number of observers of this <tt>Observable</tt> object.
  146. *
  147. * @return the number of observers of this object.
  148. */
  149. public synchronized int countObservers() {
  150. return obs.size();
  151. }
  152. }

Observer  

观察者只要实现该类即可。

3. 调停者模式 Mediator

  

mediator [ˈmēdēˌātər] :中间人

调停者模式:定义一个对象,封装一组对象的交互,从而降低对象间的耦合度,避免了对象之间的显示引用,并且可以独立的改变对象间的行为。

复杂的调用关系

引入 mediator

写个demo

Mediator 接口

  1. public interface Mediator {
  2.  
  3. void changed(Component component);
  4. }

将A,B,C...等组件 抽象出一个父类

  1. /**
  2. * A,B,C,D...抽象出一个父类 叫 Colleague
  3. * 因为 调停者 要和 A,B,C,D..组件关联 所以将它注入到各组件中(抽象到父类里)
  4. */
  5. public abstract class Component {
  6. private Mediator mediator;
  7.  
  8. public Component(Mediator mediator) {
  9. this.mediator = mediator;
  10. }
  11.  
  12. public Mediator getMediator() {
  13. return mediator;
  14. }
  15.  
  16. }

  

组件A

  1. public class ComponetA extends Component {
  2.  
  3. public ComponetA(Mediator mediator) {
  4. super(mediator);
  5. }
  6. public void start(){
  7. getMediator().changed(this);//通过Mediator 调停者 通知 其他组件
  8. }
  9. }

  

组件B

  1. public class ComponetB extends Component {
  2. public ComponetB(Mediator mediator) {
  3. super(mediator);
  4. }
  5. public void start(){
  6. getMediator().changed(this);//通过Mediator 调停者 通知 其他组件
  7. }
  8. }

  

实现 Mediator 类

  1. public class MediatorConcrete implements Mediator {
  2. //调停者 要交互 其他组件 所以 其他组件 要注入调停者里面
  3. private ComponetA colleagueA;
  4. private ComponetB colleagueB;
  5.  
  6. public void setColleague(ComponetA colleagueA, ComponetB colleagueB) {
  7. this.colleagueA = colleagueA;
  8. this.colleagueB = colleagueB;
  9. }
  10.  
  11. @Override
  12. public void changed(Component colleague) {
  13. //通知给其他组件
  14. if (colleague instanceof ComponetA) {
  15. System.out.println("hi B,ComponetA start");
  16. } else if (colleague instanceof ComponetB) {
  17. System.out.println("hi A,ComponetB start");
  18. }
  19. }
  20. }

  

测试

  1. public void test(){
  2. //实例化一个调停者
  3. MediatorConcrete mediator = new MediatorConcrete();
  4. //创建两个组件,放入调停者(要通过调停者传递消息)
  5. ComponetA a = new ComponetA(mediator);
  6. ComponetB b = new ComponetB(mediator);
  7.  
  8. //交互的组件放入 (因为一个组件change,要通知其他组件)
  9. mediator.setColleague(a,b);
  10. a.start();//a组件启动
  11.  
  12. }

运行结果 

4. 代理模式 Proxy

代理对象通常拥有一个几乎和实际对象相同的接口。它常常会控制访问,并将请求合理的转发给底层的真实对象。

Java 代理

  1. 静态代理
  2. 动态代理

静态代理

client-->subject-->proxy-->realSubject

realSubject : 委托类

proxy : 代理类

subject : 委托类和代理类的接口

静态代理中 一个委托类  realSubject 对应一个代理类 proxy 代理类在编译期间就已经确定

动态代理

Java 动态代理

动态代理的代理类 不是在Java代码中实现  是在运行期生成

1.定义接口 SubjectService

  1. public interface SubjectService {
  2. void add();
  3. }

2.定义委托类 RealSubjectServiceImpl

  1. public class RealSubjectServiceImpl implements SubjectService {
  2. @Override
  3. public void add() {
  4. System.out.println("init real sub service.");
  5. }
  6. }

3.定义 myInvocationHandler 实现java.lang.reflect.InvocationHandler接口

m.invoke(obj,args)  : 对目标对象的调用转发给 包装对象

  1. public class MyInvocationHandler implements InvocationHandler {
  2. private Object target;//目标对象
  3.  
  4. public MyInvocationHandler(Object target) {
  5. this.target = target;
  6. }
  7.  
  8. @Override
  9. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  10. System.out.println(".....before......");
  11. Object result=method.invoke(target,args);
  12. System.out.println(".....after......");
  13. return result;
  14. }
  15. public Object getProxy(){
  16. return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),target.getClass().getInterfaces(),this);
  17. }
    }

4.测试

  1. @Test
  1. public void proxyTest(){
    MyInvocationHandler handler=new MyInvocationHandler(new RealSubjectServiceImpl());
    //proxy
    SubjectService proxy= (SubjectService) handler.getProxy();
    proxy.add();
    }

运行结果

cglib动态代理  

cglib底层使用 ASM 重写 非 final 方法实现

  

1.创建 自己的方法拦截器  MyMethodInterceptor 实现  MethodInterceptor  

2.通过 net.sf.cglib.proxy.Enhancer 创建代理对象

  1. public class MyMethodInterceptor implements MethodInterceptor {
    private Object target;
  2.  
  3. public MyMethodInterceptor(Object target) {
    this.target = target;
    }
  4.  
  5. @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
    System.out.println(".....before......");
    Object result=proxy.invokeSuper(obj,args);
    System.out.println(".....before......");
    return result;
    }
  6.  
  7. public Object getProxy(){
    Enhancer enhancer=new Enhancer();
    enhancer.setCallback(this);
    enhancer.setSuperclass(target.getClass());
    return enhancer.create();
    }
    }

测试. 

  1. @Test
  2. public void cglibTest(){
  3. MyMethodInterceptor interceptor=new MyMethodInterceptor(new RealSubjectServiceImpl());
  4. SubjectService proxy= (SubjectService) interceptor.getProxy();
  5. proxy.add();
  6. }

 5. 职责链模式 chain of responsibility

职责链模式 通过给予多个对象处理请求的机会,以解除请求的发送者与接收者之间的耦合。

简单的说 :请假3天假-->leader审批-->经理审批-->人事审批

或者

我只请半天假-->leader审批-->人事审批

职责链的节点 可以自由组合

抽象一个Hander父类

  1. public abstract class Handler {
  2. private Handler next;//后续责任对象
  3.  
  4. public Handler getNext() {
  5. return next;
  6. }
  7.  
  8. public void setNext(Handler next) {
  9. this.next = next;
  10. }
  11.  
  12. public abstract void handleRequest();//处理请求
  13. }

  

A节点

  1. public class HanderA extends Handler{
  2. @Override
  3. public void handleRequest() {
  4. System.out.println("A done..");
  5. if(getNext()!=null){
  6. getNext().handleRequest();
  7. }else {
  8. System.out.println("finish..");
  9. }
  10. }
  11. }

  

B节点

  1. public class HanderB extends Handler{
  2. @Override
  3. public void handleRequest() {
  4. System.out.println("B done..");
  5. if(getNext()!=null){
  6. getNext().handleRequest();
  7. }else {
  8. System.out.println("finish..");
  9. }
  10. }
  11. }

  

c节点

  1. public class HanderC extends Handler{
  2. @Override
  3. public void handleRequest() {
  4. System.out.println("C done..");
  5. if(getNext()!=null){
  6. getNext().handleRequest();
  7. }else {
  8. System.out.println("finish..");
  9. }
  10. }
  11. }

  

测试

  1. public void test(){
  2. Handler a=new HanderA();
  3. Handler b=new HanderB();
  4. Handler c=new HanderC();
  5. a.setNext(b);
  6. b.setNext(c);
  7.  
  8. a.handleRequest();
  9. }

执行结果

 6. 享元模式 flyweight

 

享元模式 在客户对象之间提供共享对象,并且为共享对象创建职责

共享对象发生改变 时  不需要通知其他客户端 

享元模式的目的是:通过共享来支持大量细粒度对象

1.享元模式 可以 使你共享的访问 大量出现的细粒度对象

2.享元对象必须是不可变的

3.不变的部分提取出来

4.为了确保享元对象共享 ,需要强制客户端通过享元工厂来访问

5.享元工厂 做好权限限制

不变性  

可以设置成枚举  

 java 中的String就是 享元模式  

  

 1.单纯享元模式

所有的享元对象都可以共享

抽象一个接口

  1. public interface Flyweight {
  2. void operation(String state);
  3. }

实现一个享元对象

  1. public class FlyweightA implements Flyweight {
  2. //共享对象状态
  3. private Character inState;
  4.  
  5. public FlyweightA(Character inState) {
  6. this.inState = inState;
  7. }
  8.  
  9. @Override
  10. public void operation(String state) {
  11. //state 改变方法的行为 单 不改变 共享对象的状态
  12. System.out.println("param :"+state);
  13. System.out.println("state:"+inState);
  14. }
  15. }

享元工厂

  1. public class FlyweightFactory {
  2. private Map<Character,Flyweight> files=new HashMap<Character, Flyweight>();
  3. public Flyweight factory(Character state){
  4. Flyweight flyweight=files.get(state);
  5. if(flyweight==null){
  6. flyweight=new FlyweightA(state);
  7. files.put(state,flyweight);
  8. }
  9. return flyweight;
  10. }
  11. }

 

测试

  1. public class FlyweightTest {
  2.  
  3. @Test
  4. public void test() {
  5. FlyweightFactory factory = new FlyweightFactory();
  6. Flyweight flyweight = factory.factory(new Character('0'));
  7. flyweight.operation("test 1");
  8. flyweight = factory.factory(new Character('1'));
  9. flyweight.operation("test B");
  10.  
  11. }
  12. }

  

 运行结果

2.复合享元模式

复合享元模式  意思是 单个享元对象 组成一个集合,而这个集合本身不是共享的

就是 将上述的例子 instate改成一个集合

demo

接口

  1. public interface Flyweight {
  2. void operation(String state);
  3. }

单个享元

  1. public class FlyweightA implements Flyweight {
  2. //共享对象状态
  3. private Character inState;
  4.  
  5. public FlyweightA(Character inState) {
  6. this.inState = inState;
  7. }
  8.  
  9. @Override
  10. public void operation(String state) {
  11. //state 改变方法的行为 单 不改变 共享对象的状态
  12. System.out.println("param :"+state);
  13. System.out.println("state:"+inState);
  14. }
  15. }

复合享元

  1. public class FlyweightB implements Flyweight {
  2. //复合享元模式
  3. private Map<Character,Flyweight> files=new HashMap<Character, Flyweight>();
  4. @Override
  5. public void operation(String state) {
  6. for(Flyweight flyweight:files.values()){
  7. flyweight.operation(state);
  8. }
  9. }
  10.  
  11. public void add(Character key,Flyweight value){
  12. files.put(key,value);
  13. }
  14. }

  

享元工厂

  1. public class FlyweightFactory {
  2. private Map<Character,Flyweight> files=new HashMap<Character, Flyweight>();
  3. //集合工厂
  4. public Flyweight factory(List<Character> states){
  5. FlyweightB b=new FlyweightB();
  6. for(Character c:states){
  7. //调用 单个构建
  8. b.add(c,factory(c));
  9. }
  10. return b;
  11. }
  12.  
  13. //单参构建
  14. public Flyweight factory(Character state){
  15. //先从缓存中查找对象
  16. Flyweight fly = files.get(state);
  17. if(fly == null){
  18. //如果对象不存在则创建一个新的Flyweight对象
  19. fly = new FlyweightA(state);
  20. //把这个新的Flyweight对象添加到缓存中
  21. files.put(state, fly);
  22. }
  23. return fly;
  24. }
  25. }

  

测试

  1. public void test(){
  2. //工厂构建数据
  3. FlyweightFactory flyweightFactory=new FlyweightFactory();
  4. List<Character> param= Arrays.asList('0','1','2');
  5. Flyweight flyweight=flyweightFactory.factory(param);
  6.  
  7. //操作
  8. flyweight.operation("test..");
  9. }

  

运行结果

构造类

  1. 在请求 创建对象之前  ,逐渐收集创建对象的信息-->构建者模式
  2. 推迟实例化的类对象-->工厂方法模式
  3. 创建一组 有共同特征的对象-->抽象工厂
  4. 根据现有对象 创建一个对象-->原型模式
  5. 通过对象内部静态版本 重构对象-->备忘录模式

 1.构建者模式 Builder

构建者模式 :将类的实例化逻辑 转移到类的外部。

构建模式 :将构建与对象分离 。将复杂对象的构建逻辑从对象本身抽离,这样能够简化复杂对象

网上找了个例子http://www.blogjava.net/fancydeepin/archive/2012/08/05/384783.html

我们现在需要生产一个产品 :电脑

简单的描述 就是  产品(电脑) 是一个类,构建(builder) 是一个类

然后 将 产品 放入 builder中构建

看代码:

产品

  1. public abstract class Product {
  2. protected List<String> parts = new ArrayList<String>();//存储产品的各个部件
  3.  
  4. //add
  5. public void add(String part) {
  6. parts.add(part);
  7. }
  8.  
  9. //show product
  10. public void show() {
  11. for (String s : parts) {
  12. System.out.println(s);
  13. }
  14. }
  15. }

宏碁电脑

  1. public class Acer extends Product {
  2. }

戴尔电脑

  1. public class Dell extends Product {
  2. }

  

构建者接口

  1. public interface Builder {
  2. //构建产品 的几个步骤
  3. void buildCPU();
  4.  
  5. void buildMemory();
  6.  
  7. void buildGraphicsCard();
  8.  
  9. Product getResult();
  10. }

  

实现 宏碁电脑构建

  1. public class AcerBuilder implements Builder {
  2. //产品和构建分离
  3. //创建Acer产品 进行 构建
  4. private Product product=new Acer();
  5. @Override
  6. public void buildCPU() {
  7. product.add("cpu:i5");
  8. }
  9.  
  10. @Override
  11. public void buildMemory() {
  12. product.add("memory:8G");
  13. }
  14.  
  15. @Override
  16. public void buildGraphicsCard() {
  17. product.add("graphics card:HD");
  18. }
  19.  
  20. @Override
  21. public Product getResult() {
  22. return product;
  23. }
  24. }

  

实现戴尔电脑构建

  1. public class DellBuilder implements Builder {
  2. //产品和构建分离
  3. //创建Dell产品 进行 构建
  4. private Product product = new Dell();
  5.  
  6. @Override
  7. public void buildCPU() {
  8. product.add("cpu:i7");
  9. }
  10.  
  11. @Override
  12. public void buildMemory() {
  13. product.add("memory:16G");
  14. }
  15.  
  16. @Override
  17. public void buildGraphicsCard() {
  18. product.add("graphics card:HD");
  19. }
  20.  
  21. @Override
  22. public Product getResult() {
  23. return product;
  24. }
  25. }

  

指导构建过程

  1. public class Director {
  2. private Builder builder;
  3.  
  4. public Director(Builder builder) {
  5. this.builder = builder;
  6. }
  7.  
  8. public void Construct() {
  9. //控制 构建逻辑顺序
  10. builder.buildCPU();
  11. builder.buildMemory();
  12. builder.buildGraphicsCard();
  13. }
  14. }

  

测试

  1. public void test() {
  2. System.out.println("acer");
  3. AcerBuilder acerBuilder = new AcerBuilder();
  4. Director director = new Director(acerBuilder);
  5. director.Construct();
  6. //Product show
  7. acerBuilder.getResult().show();
  8.  
  9. System.out.println("..............");
  10.  
  11. System.out.println("dell");
  12. DellBuilder dellBuilder = new DellBuilder();
  13. director = new Director(dellBuilder);
  14. director.Construct();
  15. //Product show
  16. dellBuilder.getResult().show();
  17. }

  

运行结果

 2.工厂方法 factory method

工厂方法:让服务提供者 确定实例化哪个类,而不是客户端代码

网上找了个 demo http://blog.csdn.net/jason0539/article/details/23020989

简单工厂模式

简单工厂模式 又称  静态工厂模式

客户需要一辆宝马车,客户不必自己亲自造一辆宝马车 。我们可以建立一个工厂 ,工厂负责宝马车的创建,降低 客户和宝马的耦合

首先我们抽象一个BMW类

  1. public abstract class BMW {
  2. }

  

有两种型号的 BMW

  1. public class BMW320 extends BMW {
  2. public BMW320() {
  3. System.out.println("build bmw 320.");
  4. }
  5. }

BMW523

  1. public class BMW523 extends BMW {
  2. public BMW523() {
  3. System.out.println("build bmw 523.");
  4. }
  5. }

  

工厂 根据传参 创建 相应产品

  1. public class SimpleFactory {
  2. public BMW createBMW(int param) {
  3. switch (param) {
  4. case 320:
  5. return new BMW320();
  6. case 523:
  7. return new BMW523();
  8. default:
  9. break;
  10. }
  11. return null;
  12. }
  13. }

  

测试

  1. public void test(){
  2. SimpleFactory factory=new SimpleFactory();
  3. factory.createBMW(320);
  4. factory.createBMW(523);
  5. }

  

运行结果

  

工厂方法模式

简单工厂中   当客户需要 一个新产品时, simpleFactory需修改 case代码  去创建新的代码 ,这样 simpleFactory的代码会频繁改动  很是被动。这也违背了 设计模式的开闭原则。

这时  我们可以把 case部分的 静态代码抽出来,分成不同的子工厂。

Factory接口

  1. public interface Factory {
  2. BMW createBMW();
  3. }

  

320子工厂

  1. public class FactoryBMW320 implements Factory {
  2. @Override
  3. public BMW createBMW() {
  4. return new BMW320();
  5. }
  6. }

523子工厂

  1. public class FactoryBMW523 implements Factory {
  2. @Override
  3. public BMW createBMW() {
  4. return new BMW523();
  5. }
  6. }

  

测试

  1. public void test(){
  2. FactoryBMW320 factoryBMW320=new FactoryBMW320();
  3. factoryBMW320.createBMW();
  4.  
  5. FactoryBMW523 factoryBMW523=new FactoryBMW523();
  6. factoryBMW523.createBMW();
  7. }

  

运行结果

  

 3.抽象工厂 abstract factory

抽象工厂  创建不同的产品簇

还按上面的例子说 客户不是简单要一个BMW, 每个客户有 不同的  发动机和变速箱需求。

先创建两个类  发动机,变速箱

发动机

  1. public abstract class Engine {
  2. }

  

4缸发动机

  1. public class Engine4 extends Engine {
  2. public Engine4() {
  3. //生产 四缸发动机
  4. System.out.println("create N46.");
  5. }
  6. }

  

12缸发动机

  1. public class Engine12 extends Engine {
  2. public Engine12() {
  3. //生产 12缸发动机
  4. System.out.println("create M73.");
  5. }
  6. }

  

变速箱

  1. public abstract class Gearbox {
  2.  
  3. }

  

手动变速

  1. public class ManualGearbox extends Gearbox {
  2. public ManualGearbox() {
  3. System.out.println("create manual transmission.");
  4. }
  5. }

  

自动变速

  1. public class AutomaticGearbox extends Gearbox {
  2. public AutomaticGearbox() {
  3. System.out.println("create automatic transmission.");
  4. }
  5. }

  

抽象工厂

  1. public interface AbstractFactory {
  2. Engine createEngine();
  3.  
  4. Gearbox createGearbox();
  5. }

  

产品12工厂:12缸发动机,自动变速箱

  1. public class FactoryBMW12 implements AbstractFactory {
  2. @Override
  3. public Engine createEngine() {
  4. return new Engine12();
  5. }
  6.  
  7. @Override
  8. public Gearbox createGearbox() {
  9. return new AutomaticGearbox();
  10. }
  11. }

  

产品 46 工厂 :4缸发动机,手动变速

  1. public class FactoryBMW46 implements AbstractFactory {
  2. @Override
  3. public Engine createEngine() {
  4. return new Engine4();
  5. }
  6.  
  7. @Override
  8. public Gearbox createGearbox() {
  9. return new ManualGearbox();
  10. }
  11. }

  

测试

  1. public void test(){
  2. System.out.println("bmw 12 :");
  3. FactoryBMW12 factoryBMW12=new FactoryBMW12();
  4. factoryBMW12.createEngine();
  5. factoryBMW12.createGearbox();
  6. System.out.println("............");
  7.  
  8. System.out.println("bmw 46 :");
  9. FactoryBMW46 factoryBMW46=new FactoryBMW46();
  10. factoryBMW46.createEngine();
  11. factoryBMW46.createGearbox();
  12. }

  

执行结果

 4.原型模式 prototype

原型模式使用户复制对象样本来创建对象。而不是通过实例化的方式。

原型模式的核心是克隆方法,java 提供了 Cloneable接口 。

写个demo

  1. public class Student implements Cloneable {
  2. private String code;
  3. List<String> courses;
  4.  
  5. public List<String> getCourses() {
  6. return courses;
  7. }
  8.  
  9. public void setCourses(List<String> courses) {
  10. courses = courses;
  11. }
  12. public void addCourse(String course) {
  13. if(courses==null) courses=new ArrayList<String>();
  14. courses.add(course);
  15. }
  16. public String getCode() {
  17. return code;
  18. }
  19.  
  20. public void setCode(String code) {
  21. this.code = code;
  22. }
  23.  
  24. @Override
  25. protected Student clone() {
  26. try {
  27. return (Student) super.clone();
  28. } catch (CloneNotSupportedException e) {
  29. e.printStackTrace();
  30. }
  31. return null;
  32. }
  33.  
  34. @Override
  35. public String toString() {
  36. return this.code
  37. +",Courses : "+ Arrays.toString(courses.toArray());
  38. }
  39. }

  

  

原型模式 内存二进制流copy,要比直接new性能好 。

new 的时候 也许受权限限制 ,使用原型模式可以访问一些私有对象

浅拷贝

  1. public void test(){
  2. Student student=new Student();
  3. student.setCode("001");
  4. student.addCourse("math");
  5.  
  6. Student studentB=student.clone();
  7. studentB.setCode("001B");
  8. studentB.addCourse("java");
  9. studentB.addCourse("C#");
  10. System.out.println(student.toString());
  11. System.out.println(studentB.toString());
  12.  
  13. }

 

输出

可以发现  studenB的  Courses变化 会影响到 原始Student

因为 Object提供的clone只Copy对象 对象中数组和引用对象都未copy,指向的还是元数据的 地址。 

 深拷贝

可以通过流式copy进行深copy

  1. public class Teacher implements Serializable{
  2. private String code;
  3. List<String> courses;
  4.  
  5. public List<String> getCourses() {
  6. return courses;
  7. }
  8.  
  9. public void setCourses(List<String> courses) {
  10. courses = courses;
  11. }
  12. public void addCourse(String course) {
  13. if(courses==null) courses=new ArrayList<String>();
  14. courses.add(course);
  15. }
  16. public String getCode() {
  17. return code;
  18. }
  19.  
  20. public void setCode(String code) {
  21. this.code = code;
  22. }
  23.  
  24. @Override
  25. public String toString() {
  26. return this.code
  27. +",Courses : "+ Arrays.toString(courses.toArray());
  28. }
  29. }

  

流 copy

  1. public void testDeep(){
  2. try {
  3. Teacher teacher=new Teacher();
  4. teacher.setCode("001");
  5. teacher.addCourse("tech math");
  6.  
  7. //对象 写入缓存 bytes
  8. //申明缓存空间
  9. ByteOutputStream bytes=new ByteOutputStream();
  10. //申明 对象写入
  11. ObjectOutputStream out=new ObjectOutputStream(bytes);
  12. //对象写入
  13. out.writeObject(teacher);
  14.  
  15. //bytes中读取对象
  16. ObjectInputStream inputStream=new ObjectInputStream(new ByteArrayInputStream(bytes.getBytes())) ;
  17. Teacher teacherB= (Teacher) inputStream.readObject();
  18. teacherB.setCode("001B");
  19. teacherB.addCourse("tech java");
  20. System.out.println(teacher.toString());
  21. System.out.println(teacherB.toString());
  22. } catch (Exception e) {
  23. e.printStackTrace();
  24. }
  25.  
  26. }

  

运行结果

 5.备忘录模式 Memento

备忘录模式的目的是 为对象状态 提供存储和恢复功能。

备忘录模式的结构

Originator [əˈrijəˌnātər]

Caretaker [Care taker] 管理人

  1. 发起人:记录当前时刻内部状态,负责定义哪些属于备份范围的状态,负责创建和恢复备忘数据。
  2. 备忘录:负责存储 发起人对象的内部状态,需要的时候提供 发起人需要的内部状态
  3. 管理角色:对备忘录进行管理,保存和提供备忘数据。

发起人代码

  1. public class Originator {
  2. private String state="";
  3.  
  4. public String getState() {
  5. return state;
  6. }
  7.  
  8. public void setState(String state) {
  9. this.state = state;
  10. }
  11. //创建备忘状态
  12. public Memento createMemento(){
  13. return new Memento(this.state);
  14. }
  15. //恢复备忘状态
  16. public void restoreMemento(Memento memento){
  17. this.setState(memento.getState());
  18. }
  19. }

备忘录

  1. public class Memento {
  2. private String state="";
  3.  
  4. public Memento(String state) {
  5. this.state = state;
  6. }
  7.  
  8. public String getState() {
  9. return state;
  10. }
  11.  
  12. public void setState(String state) {
  13. this.state = state;
  14. }
  15. }

管理者

  1. public class Caretaker {
  2. private Memento memento;
  3.  
  4. public Memento getMemento() {
  5. return memento;
  6. }
  7.  
  8. public void setMemento(Memento memento) {
  9. this.memento = memento;
  10. }
  11. }

  

测试

  1. public void test(){
  2. Originator originator=new Originator();
  3. originator.setState("init");
  4. System.out.println(originator.getState());
  5.  
  6. //管理员 保存 现有状态
  7. Caretaker caretaker=new Caretaker();
  8. caretaker.setMemento(originator.createMemento());
  9.  
  10. //更新状态
  11. originator.setState("running");
  12. System.out.println(originator.getState());
  13.  
  14. //恢复状态
  15. originator.restoreMemento(caretaker.getMemento());
  16.  
  17. System.out.println(originator.getState());
  18. }

  

执行结果

多状态 备忘

将 对象的属性放在map里

操作类

不同类 实现同一操作时 采用不同的方式 。类似java的多态 ,多态的设计思路被多种设计模式使用。

  1. 在方法中实现算法,推迟对算法步骤的定义,使得子类能够重新实现-->模板方法模式
  2. 将操作分散,使得每个类都能够表示不同的状态-->状态模式
  3. 封装操作,使得实现都可以相互替换-->策略模式
  4. 用对象来封装方法调用-->命令模式
  5. 将操作分散,使得每个实现运用到不同类型的集合-->解析器模式

 1.模板方法模式 template mothed

  

 模板方法:抽象一些步骤或将它定义在接口中,以便其他类可以实现这一步骤。

比如 我们去乘车  大致分为  买票-->进站安检-->检票-->入座

我现在搞一个系统 乘坐汽车,乘坐火车,乘坐地铁 都用该系统

写个demo

先抽象一个公共父类 定义基本的逻辑框架

  1. public abstract class Ride {
  2. //模板 方法 final类型 子类不可以修改
  3. public final void action(){
  4. buyTicket();
  5. securityCheck();
  6. checkIn();
  7. seated();
  8. doStarted();
  9. }
  10. //购票
  11. protected abstract void buyTicket();
  12. //进站安检
  13. protected abstract void securityCheck();
  14. //检票
  15. protected abstract void checkIn();
  16. //入座
  17. protected abstract void seated();
  18. //钩子方法 ,子类可以不必要实现,如果有需求可以写
  19. protected void doStarted(){
  20. System.out.println("车辆启动..");
  21. }
  22. }

  

汽车出行

  1. public class Bus extends Ride {
  2.  
  3. @Override
  4. protected void buyTicket() {
  5. System.out.println("buy a bus ticket.");
  6. }
  7.  
  8. @Override
  9. protected void securityCheck() {
  10.  
  11. System.out.println("bus station security check.");
  12. }
  13.  
  14. @Override
  15. protected void checkIn() {
  16. System.out.println("bus station check in.");
  17. }
  18.  
  19. @Override
  20. protected void seated() {
  21. //按票入座
  22. System.out.println("ticket seat.");
  23. }
  24. }

  

地铁出行

  1. public class Subway extends Ride {
  2.  
  3. @Override
  4. protected void buyTicket() {
  5. System.out.println("buy a subway ticket.");
  6. }
  7.  
  8. @Override
  9. protected void securityCheck() {
  10.  
  11. System.out.println("subway station security check.");
  12. }
  13.  
  14. @Override
  15. protected void checkIn() {
  16. System.out.println("subway station check in.");
  17. }
  18.  
  19. @Override
  20. protected void seated() {
  21. //随便坐
  22. System.out.println("Sit casually.");
  23. }
  24. }

  

测试

  1. public void test(){
  2. Ride ride=new Bus();
  3. ride.action();
  4. System.out.println(".....");
  5. ride=new Subway();
  6. ride.action();
  7.  
  8. }

运行结果

 2.状态模式

程序中 经常 因状态不同,执行的不同逻辑代码 。状态模式: 就是将 这些状态 分为不同的状态对象,

且 这些状态对象 有自己的状态 行为。解耦

网上找了个例子

四种颜色

Red,
White,
Blue,
Black

有 pull和  push两种操作

Color类

  1. public enum Color {
  2. Red,
  3. White,
  4. Blue,
  5. Black
  6. }

操作管理类

  1. public class Context {
  2. private Color color;
  3.  
  4. public Context(Color color) {
  5. this.color = color;
  6. }
  7.  
  8. public void push(){
  9. //red->white->blue->black
  10. if(color==Color.Red) color=Color.White;
  11. else if(color==Color.White) color=Color.Blue;
  12. else if(color==Color.Blue) color=Color.Black;
  13. }
  14. public void pull(){
  15. //red<-white<-blue<-black
  16. if(color==Color.Black) color=Color.Blue;
  17. else if(color==Color.Blue) color=Color.White;
  18. else if(color==Color.White) color=Color.Red;
  19.  
  20. }
  21. }

测试

  1. public void test(){
  2. Context context=new Context(Color.Red);
  3. context.push();
  4. System.out.println(context.getColor().name());
  5. context.pull();
  6. System.out.println(context.getColor().name());
  7. }

结果

改用状态模式

  1. public abstract class State {
  2. protected abstract void push(Context2 context);
  3. protected abstract void pull(Context2 context);
  4. protected abstract Color getColor();
  5.  
  6. }

 

  1. public class RedState extends State {
  2. @Override
  3. protected void push(Context2 context) {
  4. context.setState(new WhiteState());
  5. }
  6.  
  7. @Override
  8. protected void pull(Context2 context) {
  9. context.setState(new RedState());
  10. }
  11.  
  12. @Override
  13. protected Color getColor() {
  14. return Color.Red;
  15. }
  16. }

 

  1. public class WhiteState extends State {
  2. @Override
  3. protected void push(Context2 context) {
  4. context.setState(new BlueState());
  5. }
  6.  
  7. @Override
  8. protected void pull(Context2 context) {
  9. context.setState(new RedState());
  10. }
  11.  
  12. @Override
  13. protected Color getColor() {
  14. return Color.White;
  15. }
  16. }

  

  1. public class BlueState extends State {
  2. @Override
  3. protected void push(Context2 context) {
  4. context.setState(new BlackState());
  5. }
  6.  
  7. @Override
  8. protected void pull(Context2 context) {
  9. context.setState(new WhiteState());
  10. }
  11.  
  12. @Override
  13. protected Color getColor() {
  14. return Color.Blue;
  15. }
  16. }

  

 

  1. public class BlackState extends State {
  2. @Override
  3. protected void push(Context2 context) {
  4. context.setState(new BlackState());
  5. }
  6.  
  7. @Override
  8. protected void pull(Context2 context) {
  9. context.setState(new BlueState());
  10. }
  11.  
  12. @Override
  13. protected Color getColor() {
  14. return Color.Black;
  15. }
  16. }

  

测试

  1. public void test2(){
  2. Context2 context2=new Context2(new RedState());
  3. context2.push();
  4. System.out.println(context2.getState().getColor());
  5. context2.pull();
  6. System.out.println(context2.getState().getColor());
  7. }

  

运行结果

3.策略模式 strategy

strategy [ˈstratəjē]

策略模式 就是 将公共操作 ,在不同类中分别实现,也就是继承公共的接口或父类  。再用策略调用者调用自己需要的策略。

demo:

1.策略接口

  1. public interface Strategy {
  2. void compress();
  3. }

2.rar压缩算法实现

  1. public class RarStrategy implements Strategy {
  2. @Override
  3. public void compress() {
  4. System.out.println("execute rar compression");
  5. }
  6. }

3.zip压缩算法实现

  1. public class ZipStrategy implements Strategy {
  2. @Override
  3. public void compress() {
  4. System.out.println("execute zip compression");
  5. }
  6. }

4.调用者类

  1. public class Context {
  2. private Strategy strategy;
  3.  
  4. public Context(Strategy strategy) {
  5. this.strategy = strategy;
  6. }
  7.  
  8. public void executeCompress(){
  9. strategy.compress();
  10. }
  11. }

5.测试

  1. public void test(){
  2. Context context=new Context(new RarStrategy());
  3. context.executeCompress();
  4. context=new Context(new ZipStrategy());
  5. context.executeCompress();
  6. }

  

执行结果

 4.命令模式

  

命令模式的目的是 将请求 封装到 类内部

命令模式可以将请求封装在一个对象中  允许你可以像管理对象一样去 管理方法 ,传递 并且在适合的机会调用它

  

网上找了个例子 :http://blog.csdn.net/jason0539/article/details/45110355  

 开关电视机的请求

现在设置 请求命令接口

  1. public interface Command {
  2. void execute();
  3. }

然后 建立一个 TV对象 作为命令的接收者

  1. public class TV {
  2.  
  3. void turnOn(){
  4. System.out.println("The TV is turn on.");
  5. }
  6. void turnOff(){
  7. System.out.println("The TV is turn off.");
  8. }
  9. }

  

开机命令

  1. public class CommandOn implements Command {
  2. private TV tv;
  3.  
  4. public CommandOn(TV tv) {
  5. this.tv = tv;
  6. }
  7.  
  8. @Override
  9. public void execute() {
  10. tv.turnOn();
  11. }
  12. }

  

关机命令

  1. public class CommandOff implements Command {
  2. private TV tv;
  3.  
  4. public CommandOff(TV tv) {
  5. this.tv = tv;
  6. }
  7.  
  8. @Override
  9. public void execute() {
  10. tv.turnOff();
  11. }
  12. }

  

控制 器   就像遥控器

  1. public class Control {
  2. private CommandOn commandOn;
  3. private CommandOff commandOff;
  4.  
  5. public Control(CommandOn commandOn, CommandOff commandOff) {
  6. this.commandOn = commandOn;
  7. this.commandOff = commandOff;
  8. }
  9.  
  10. public void turnOn(){
  11. commandOn.execute();
  12. }
  13.  
  14. public void turnOff(){
  15. commandOff.execute();
  16. }
  17. }

 

测试

  1. public void test() {
  2. TV tv = new TV();
  3. CommandOn commandOn = new CommandOn(tv);
  4. CommandOff commandOff = new CommandOff(tv);
  5. Control control=new Control(commandOn,commandOff);
  6. control.turnOn();
  7. control.turnOff();
  8. }

执行结果

本demo将命令 开机和关机命令 封装 传递 ,并在需要的时候触发

  

5.解析器模式 Interpreter 

扩展型设计模式 

  1. 让开发者动态组合对象行为-->装饰器模式
  2. 提供一个方法 来顺序访问 集合中的元素-->迭代器模式
  3. 允许开发者定义新的操作 而无需改变 分层体系中的类-->访问者模式

1.装饰器模式 decorator

decorator [ˈdekəˌrātər]

经典的装饰器模式 就是java中的流处理

  1. public void test(){
  2. try {
  3. FileWriter file=new FileWriter(new File("E://test//test.txt"));
  4. BufferedWriter writer=new BufferedWriter(file);
  5. writer.write("this is test file.");
  6. writer.flush();
  7. writer.close();
  8. } catch (IOException e) {
  9. e.printStackTrace();
  10. }
  11. }

这段代码中 我们从 FileWriter 组合成BufferWriter 最后输入文本;

通过构造器传入参数 ,产生了新的对象行为。  

查看下  源码

2.迭代器模式 Iterator

为顺序访问集合提供一种方式

  1. /*
  2. * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  3. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  4. *
  5. *
  6. */
  7.  
  8. package java.util;
  9.  
  10. import java.util.function.Consumer;
  11.  
  12. /**
  13. * An iterator over a collection. {@code Iterator} takes the place of
  14. * {@link Enumeration} in the Java Collections Framework. Iterators
  15. * differ from enumerations in two ways:
  16. *
  17. * <ul>
  18. * <li> Iterators allow the caller to remove elements from the
  19. * underlying collection during the iteration with well-defined
  20. * semantics.
  21. * <li> Method names have been improved.
  22. * </ul>
  23. *
  24. * <p>This interface is a member of the
  25. * <a href="{@docRoot}/../technotes/guides/collections/index.html">
  26. * Java Collections Framework</a>.
  27. *
  28. * @param <E> the type of elements returned by this iterator
  29. *
  30. * @author Josh Bloch
  31. * @see Collection
  32. * @see ListIterator
  33. * @see Iterable
  34. * @since 1.2
  35. */
  36. public interface Iterator<E> {
  37. /**
  38. * Returns {@code true} if the iteration has more elements.
  39. * (In other words, returns {@code true} if {@link #next} would
  40. * return an element rather than throwing an exception.)
  41. *
  42. * @return {@code true} if the iteration has more elements
  43. */
  44. boolean hasNext();
  45.  
  46. /**
  47. * Returns the next element in the iteration.
  48. *
  49. * @return the next element in the iteration
  50. * @throws NoSuchElementException if the iteration has no more elements
  51. */
  52. E next();
  53.  
  54. /**
  55. * Removes from the underlying collection the last element returned
  56. * by this iterator (optional operation). This method can be called
  57. * only once per call to {@link #next}. The behavior of an iterator
  58. * is unspecified if the underlying collection is modified while the
  59. * iteration is in progress in any way other than by calling this
  60. * method.
  61. *
  62. * @implSpec
  63. * The default implementation throws an instance of
  64. * {@link UnsupportedOperationException} and performs no other action.
  65. *
  66. * @throws UnsupportedOperationException if the {@code remove}
  67. * operation is not supported by this iterator
  68. *
  69. * @throws IllegalStateException if the {@code next} method has not
  70. * yet been called, or the {@code remove} method has already
  71. * been called after the last call to the {@code next}
  72. * method
  73. */
  74. default void remove() {
  75. throw new UnsupportedOperationException("remove");
  76. }
  77.  
  78. /**
  79. * Performs the given action for each remaining element until all elements
  80. * have been processed or the action throws an exception. Actions are
  81. * performed in the order of iteration, if that order is specified.
  82. * Exceptions thrown by the action are relayed to the caller.
  83. *
  84. * @implSpec
  85. * <p>The default implementation behaves as if:
  86. * <pre>{@code
  87. * while (hasNext())
  88. * action.accept(next());
  89. * }</pre>
  90. *
  91. * @param action The action to be performed for each element
  92. * @throws NullPointerException if the specified action is null
  93. * @since 1.8
  94. */
  95. default void forEachRemaining(Consumer<? super E> action) {
  96. Objects.requireNonNull(action);
  97. while (hasNext())
  98. action.accept(next());
  99. }
  100. }

如果一个类 支持 for循环 必须实现Iterable接口 ,并提供 Iterator方法

  1. public interface Iterable <T> {
  2. java.util.Iterator<T> iterator();
  3.  
  4. default void forEach(java.util.function.Consumer<? super T> consumer) { /* compiled code */ }
  5.  
  6. default java.util.Spliterator<T> spliterator() { /* compiled code */ }
  7. }

  

比如我们经常使用的 ArrayList

 3.访问者 visitor模式

访问者模式的意图是 不改变类层次结构前提下,对该层次结构进行扩展。

 

  

  

  

  

  

  

  

  

java设计模式学习笔记的更多相关文章

  1. java设计模式学习笔记--接口隔离原则

    接口隔离原则简述 客户端不应该依赖它不需要的接口,即一个类对另一个类的依赖应建立在最小的接口上 应用场景 如下UML图 类A通过接口Interface1依赖类B,类C通过接口Interface1依赖类 ...

  2. java设计模式学习笔记--单一职责原则

    单一职责原则注意事项和细节 1.降低类的复杂度,一个类只负责一项职责 2.提高可读性,可维护性 3.降低变更引起的风险 4.通常情况下,我们应当遵守单一职责原则,只有逻辑足够简单,才可以在代码级违反单 ...

  3. java设计模式学习笔记--浅谈设计模式

    设计模式的目的 编写软件的过程中,程序员面临着来自耦合性,内聚性以及可维护性,可扩展性,重用性,灵活性等多方面的挑战.设计模式为了让程序具有更好的 1.代码重用性(即:相同功能的代码,不用多次编写) ...

  4. Java设计模式学习笔记(五) 单例模式

    前言 本篇是设计模式学习笔记的其中一篇文章,如对其他模式有兴趣,可从该地址查找设计模式学习笔记汇总地址 1. 使用单例模式的原因 以Windows任务管理器为例,在Windows系统中,任务管理器是唯 ...

  5. Java设计模式学习笔记(二) 简单工厂模式

    前言 本篇是设计模式学习笔记的其中一篇文章,如对其他模式有兴趣,可从该地址查找设计模式学习笔记汇总地址 正文开始... 1. 简介 简单工厂模式不属于GoF23中设计模式之一,但在软件开发中应用也较为 ...

  6. Java设计模式学习笔记(三) 工厂方法模式

    前言 本篇是设计模式学习笔记的其中一篇文章,如对其他模式有兴趣,可从该地址查找设计模式学习笔记汇总地址 1. 简介 上一篇博客介绍了简单工厂模式,简单工厂模式存在一个很严重的问题: 就是当系统需要引入 ...

  7. Java设计模式学习笔记(四) 抽象工厂模式

    前言 本篇是设计模式学习笔记的其中一篇文章,如对其他模式有兴趣,可从该地址查找设计模式学习笔记汇总地址 1. 抽象工厂模式概述 工厂方法模式通过引入工厂等级结构,解决了简单工厂模式中工厂类职责太重的问 ...

  8. Java设计模式学习笔记(一) 设计模式概述

    前言 大约在一年前学习过一段时间的设计模式,但是当时自己的学习方式比较低效,也没有深刻的去理解.运用所学的知识. 所以现在准备系统的再重新学习一遍,写一个关于设计模式的系列博客. 废话不多说,正文开始 ...

  9. Java设计模式学习笔记,一:单例模式

    开始学习Java的设计模式,因为做了很多年C语言,所以语言基础的学习很快,但是面向过程向面向对象的编程思想的转变还是需要耗费很多的代码量的.所有希望通过设计模式的学习,能更深入的学习. 把学习过程中的 ...

  10. Java设计模式学习笔记(单例模式)

    最近一直在看<Head First设计模式>,这本书写的确实是很不错的,专注于怎么用最简单的方式最通俗的语言让人了解设计模式.据说GoF的设计模式那本书写的很好,是一本经典,但是就是难懂, ...

随机推荐

  1. 10个最新手机美食APP界面设计欣赏

    移动软件时代,简单下载美食app,动动手指,滑动几下手机屏幕,即可足不出户,搜索,预定和购买各路美食.然而,对于作为手机app UI 界面设计师的你来说,最大的问题并不在于如何使用这些美食软件来方便生 ...

  2. Java Persistence with MyBatis 3(中文版) 第五章 与Spring集成

    MyBatis-Spring是MyBatis框架的子模块,用来提供与当前流行的依赖注入框架Spring的无缝集成. Spring框架是一个基于依赖注入(Dependency Injection)和面向 ...

  3. Java中的Set,List,Map的区别

    1. 对JAVA的集合的理解是想对于数组 数组是大小固定的,并且同一个数组只能存放类型一样的数据(基本类型/引用类型) JAVA集合可以存储和操作数目不固定的一组数据. 所有的JAVA集合都位于 ja ...

  4. 在 CentOS 上部署 Nginx 环境

    这里的案例主要通过虚拟机( vmware workstation (14) )的方式安装 Center OS 到本地环境 资源下载:  vmware workstation   / CentOS 本次 ...

  5. firefox ubuntu 中文包

    sudo apt-get install firefox-locale-zh-hans

  6. C# 判断是否是在设计模式下有效的方法

    public static bool IsDesignMode() { bool returnFlag = false; #if DEBUG if (LicenseManager.UsageMode ...

  7. 部署图像深度学习Web网站

    1. 内网穿透 2. 深度学习Web化 https://www.cnblogs.com/haolujun/p/9778939.html

  8. mysql数据库使用sql查询数据库大小及表大小

    网上查了很多资料,最后发现一个可行的,分享如下: 数据库大小查询: select concat(round(sum(DATA_LENGTH/1024/1024),2),'M') from inform ...

  9. C# 连接Oracle,并调用存储过程(存在返回值),C# 调用sql存储过程

    1.获取Oracle表格信息 public OracleHelpers(string ConnStr) { ConnectionString = ConnStr; conn = new OracleC ...

  10. C# DataGridView添加右键菜单的简单应用

    首先,参考了下以下文章: https://blog.csdn.net/qin_zhangyongheng/article/details/23773757 感谢. 项目中要在DataGridView中 ...