JAVA的设计模式浅谈

来源:互联网 发布:一键切换ip mac 编辑:程序博客网 时间:2024/05/05 11:49

java设计模式,本人贴上自己写的各种模式的实现代码来讲解;希望大家能学到。

                                                BY-- 何泽江(凯捷国际)

创建模式

1.工厂方法模式(Factory Method)  将程序中创建对象的操作,单独出来处理,创建一个产品的工厂接口,把实际的工作转移到具体的子类。大大提高了系统扩展的柔性,接口的抽象化处理给相互依赖的对象创建提供了最好的抽象模式。

[java] view plaincopyprint?
  1. public class TestFactoryMethod  
  2.   
  3. public static void main(String[] args)  
  4.   
  5. AnimalFactory af=new DogFactory();  
  6.   
  7. Animal1 a=af.getAnimal();  
  8.   
  9.  
  10.   
  11.  
  12.   
  13. abstract class Animal1{}  
  14.   
  15. class Dog1 extends Animal1{}  
  16.   
  17. class Cat1 extends Animal1{}  
  18.   
  19.   
  20.   
  21. abstract class AnimalFactory{  
  22.   
  23. public abstract Animal1 getAnimal();  
  24.   
  25.  
  26.   
  27. class DogFactory extends AnimalFactory{  
  28.   
  29. public Animal1 getAnimal(){  
  30.   
  31. System.out.println("Dog");  
  32.   
  33. return new Dog1();  
  34.   
  35.  
  36.   
  37.  
  38.   
  39. class CatFactory extends AnimalFactory{  
  40.   
  41. public Animal1 getAnimal(){  
  42.   
  43. System.out.println("Cat");  
  44.   
  45. return new Cat1();  
  46.   
  47.  
  48.   
  49.   
public class TestFactoryMethod { public static void main(String[] args) { AnimalFactory af=new DogFactory(); Animal1 a=af.getAnimal(); } } abstract class Animal1{} class Dog1 extends Animal1{} class Cat1 extends Animal1{} abstract class AnimalFactory{ public abstract Animal1 getAnimal(); } class DogFactory extends AnimalFactory{ public Animal1 getAnimal(){ System.out.println("Dog"); return new Dog1(); } } class CatFactory extends AnimalFactory{ public Animal1 getAnimal(){ System.out.println("Cat"); return new Cat1(); } }

 

2.抽象工厂模式(Abstract Factory) 针对多个产品等级的情况,而工厂方法模式针对单一产品等级的情况。
[java] view plaincopyprint?
  1. import java.awt.*;  
  2.   
  3. import javax.swing.*;  
  4.   
  5. import java.awt.event.*;  
  6.   
  7. public class TestAbstractFactory  
  8.   
  9. public static void main(String[] args)  
  10.   
  11. GUIFactory fact=new SwingFactory();  
  12.   
  13. Frame f=fact.getFrame();  
  14.   
  15. Component c1=fact.getButton();  
  16.   
  17. Component c2=fact.getTextField();  
  18.   
  19.   
  20.   
  21. f.setSize(500,300);  
  22.   
  23. f.setLayout(new FlowLayout());  
  24.   
  25. f.add(c1);  
  26.   
  27. f.add(c2);  
  28.   
  29. f.setVisible(true);  
  30.   
  31.   
  32.   
  33. f.addWindowListener(new WindowAdapter(){  
  34.   
  35. public void windowClosing(WindowEvent e){  
  36.   
  37. System.exit(0);  
  38.   
  39.  
  40.   
  41. });  
  42.   
  43.  
  44.   
  45.  
  46.   
  47. abstract class GUIFactory{  
  48.   
  49. public abstract Component getButton();  
  50.   
  51. public abstract Component getTextField();  
  52.   
  53. public abstract Frame getFrame();  
  54.   
  55.  
  56.   
  57. class AWTFactory extends GUIFactory{  
  58.   
  59. public Component getButton()  
  60.   
  61. return new Button("AWT Button");  
  62.   
  63.  
  64.   
  65. public Frame getFrame()  
  66.   
  67. return new Frame("AWT Frame");  
  68.   
  69.  
  70.   
  71. public Component getTextField()  
  72.   
  73. return new TextField(20);  
  74.   
  75.  
  76.   
  77.   
  78.   
  79.  
  80.   
  81. class SwingFactory extends GUIFactory{  
  82.   
  83. public Component getButton()  
  84.   
  85. return new JButton("Swing Button");  
  86.   
  87.  
  88.   
  89. public Frame getFrame()  
  90.   
  91. return new JFrame("Swing Frame");  
  92.   
  93.  
  94.   
  95. public Component getTextField()  
  96.   
  97. return new JTextField(20);  
  98.   
  99.  
  100.   
  101.   
import java.awt.*; import javax.swing.*; import java.awt.event.*; public class TestAbstractFactory { public static void main(String[] args) { GUIFactory fact=new SwingFactory(); Frame f=fact.getFrame(); Component c1=fact.getButton(); Component c2=fact.getTextField(); f.setSize(500,300); f.setLayout(new FlowLayout()); f.add(c1); f.add(c2); f.setVisible(true); f.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); } } abstract class GUIFactory{ public abstract Component getButton(); public abstract Component getTextField(); public abstract Frame getFrame(); } class AWTFactory extends GUIFactory{ public Component getButton() { return new Button("AWT Button"); } public Frame getFrame() { return new Frame("AWT Frame"); } public Component getTextField() { return new TextField(20); } } class SwingFactory extends GUIFactory{ public Component getButton() { return new JButton("Swing Button"); } public Frame getFrame() { return new JFrame("Swing Frame"); } public Component getTextField() { return new JTextField(20); } }
3.单例模式(Singleton)改善全局变量和命名空间的冲突,可以说是一种改良了的全局变量。这种一个类只有一个实例,且提供一个访问全局点的方式,更加灵活的保证了实例的创建和访问约束。系统中只有一个实例,因此构造方法应该为私有饿汉式:类加载时直接创建静态实例 懒汉式:第一次需要时才创建一个实例,那么newInstance方法要加同步饿汉式比懒汉式要好,尽管资源利用率要差。但是不用同步。
[java] view plaincopyprint?
  1. public class TestSingleton  
  2.   
  3. public static void main(String[] args)  
  4.   
  5.   
  6.   
  7.  
  8.   
  9.  
  10.   
  11. class ClassA{ //饿汉式  
  12.   
  13. private static ClassA i=new ClassA();  
  14.   
  15. public static ClassA newInstance(){  
  16.   
  17. return i;  
  18.   
  19.  
  20.   
  21. private ClassA(){}  
  22.   
  23.  
  24.   
  25. class ClassB{ //懒汉式  
  26.   
  27. private static ClassB i=null 
  28.   
  29. public static synchronized ClassB newInstance(){  
  30.   
  31. if (i==nulli=new ClassB();  
  32.   
  33. return i;  
  34.   
  35.  
  36.   
  37. private ClassB(){}  
  38.   
  39.   
public class TestSingleton { public static void main(String[] args) { } } class ClassA{ //饿汉式 private static ClassA i=new ClassA(); public static ClassA newInstance(){ return i; } private ClassA(){} } class ClassB{ //懒汉式 private static ClassB i=null; public static synchronized ClassB newInstance(){ if (i==null) i=new ClassB(); return i; } private ClassB(){} }

4.建造模式(Builder)将一个对象的内部表象和建造过程分割,一个建造过程可以造出不同表象的对象。可简化为模版方法模式.

[java] view plaincopyprint?
  1. public class TestBuilder   
  2.   
  3. public static void main(String[] args)   
  4.   
  5. Builder b=new BuilderImpl1();   
  6.   
  7. Director d=new Director(b);   
  8.   
  9. Product p=d.createProduct();   
  10.   
  11.  
  12.   
  13.   
  14.   
  15.  
  16.   
  17.  interface Builder{   
  18.   
  19. void buildPart1();   
  20.   
  21. void buildPart2();   
  22.   
  23. void buildPart3();   
  24.   
  25. Product getProduct();   
  26.   
  27.   
  28.   
  29. class BuilderImpl1 implements Builder{  
  30.   
  31.   
  32.   
  33. public void buildPart1()   
  34.   
  35. System.out.println("create part1");  
  36.   
  37.   
  38.   
  39.   
  40.   
  41. public void buildPart2()   
  42.   
  43. System.out.println("create part2");  
  44.   
  45.  
  46.   
  47.   
  48.   
  49. public void buildPart3()   
  50.   
  51. System.out.println("create part3");   
  52.   
  53.  
  54.   
  55.   
  56.   
  57. public Product getProduct()   
  58.   
  59. return new Product();   
  60.   
  61.  
  62.   
  63.   
  64.   
  65.  
  66.   
  67.   
  68.   
  69. class Director{   
  70.   
  71. Builder b;   
  72.   
  73. public Director(Builder b){   
  74.   
  75. this.b=b;   
  76.   
  77.   
  78.   
  79. public Product createProduct(){   
  80.   
  81. b.buildPart1(); b.buildPart2();   
  82.   
  83. b.buildPart3();   
  84.   
  85. return b.getProduct();   
  86.   
  87.  
  88.   
  89.    
  90.   
  91. class Product{}   
public class TestBuilder { public static void main(String[] args) { Builder b=new BuilderImpl1(); Director d=new Director(b); Product p=d.createProduct(); } } interface Builder{ void buildPart1(); void buildPart2(); void buildPart3(); Product getProduct(); } class BuilderImpl1 implements Builder{ public void buildPart1() { System.out.println("create part1"); } public void buildPart2() { System.out.println("create part2"); } public void buildPart3() { System.out.println("create part3"); } public Product getProduct() { return new Product(); } } class Director{ Builder b; public Director(Builder b){ this.b=b; } public Product createProduct(){ b.buildPart1(); b.buildPart2(); b.buildPart3(); return b.getProduct(); } } class Product{}

5.原型模式(ProtoType)通过一个原型对象来创建一个新对象(克隆)。Java中要给出Clonable接口的实现,具体类要实现这个接口,并给出clone()方法的实现细节,这就是简单原型模式的应用。 浅拷贝:只拷贝简单属性的值和对象属性的地址 深拷贝:拷贝本对象引用的对象,有可能会出现循环引用的情况。可以用串行化解决深拷贝。写到流里再读出来,这时会是一个对象的深拷贝结果。

[java] view plaincopyprint?
  1. import java.io.*;  
  2.   
  3. public class TestClonealbe  
  4.   
  5. public static void main(String[] args) throws Exception  
  6.   
  7. Father f=new Father();  
  8.   
  9.   
  10.   
  11. User u1=new User("123456",f);  
  12.   
  13. User u2=(User)u1.clone();  
  14.   
  15. System.out.println(u1==u2);  
  16.   
  17. System.out.println(u1.f==u2.f);  
  18.   
  19.  
  20.   
  21.  
  22.   
  23. class User implements Cloneable,Serializable{  
  24.   
  25. String password;  
  26.   
  27. Father f;  
  28.   
  29. public User(String password,Father f){  
  30.   
  31. this.password=password;  
  32.   
  33. this.f=f;  
  34.   
  35.  
  36.   
  37. public Object clone() throws CloneNotSupportedException  
  38.   
  39. //return super.clone();   
  40.   
  41. ObjectOutputStream out=null 
  42.   
  43. ObjectInputStream in=null 
  44.   
  45. try  
  46.   
  47. ByteArrayOutputStream bo=new ByteArrayOutputStream();  
  48.   
  49. out new ObjectOutputStream(bo);  
  50.   
  51. out.writeObject(this);  
  52.   
  53. out.flush();  
  54.   
  55. byte[] bs=bo.toByteArray();  
  56.   
  57.   
  58.   
  59. ByteArrayInputStream bi=new ByteArrayInputStream(bs);  
  60.   
  61. in new ObjectInputStream(bi);  
  62.   
  63. Object o=in.readObject();  
  64.   
  65.   
  66.   
  67. return o;  
  68.   
  69. catch (IOException e)  
  70.   
  71. e.printStackTrace();  
  72.   
  73. return null 
  74.   
  75. catch (ClassNotFoundException e)  
  76.   
  77. e.printStackTrace();  
  78.   
  79. return null 
  80.   
  81.  
  82.   
  83. finally 
  84.   
  85. try  
  86.   
  87. out.close();  
  88.   
  89. in.close();  
  90.   
  91. catch (IOException e)  
  92.   
  93. e.printStackTrace();  
  94.   
  95.  
  96.   
  97.  
  98.   
  99.  
  100.   
  101.  
  102.   
  103. class Father implements Serializable{}  
import java.io.*; public class TestClonealbe { public static void main(String[] args) throws Exception { Father f=new Father(); User u1=new User("123456",f); User u2=(User)u1.clone(); System.out.println(u1==u2); System.out.println(u1.f==u2.f); } } class User implements Cloneable,Serializable{ String password; Father f; public User(String password,Father f){ this.password=password; this.f=f; } public Object clone() throws CloneNotSupportedException { //return super.clone(); ObjectOutputStream out=null; ObjectInputStream in=null; try { ByteArrayOutputStream bo=new ByteArrayOutputStream(); out = new ObjectOutputStream(bo); out.writeObject(this); out.flush(); byte[] bs=bo.toByteArray(); ByteArrayInputStream bi=new ByteArrayInputStream(bs); in = new ObjectInputStream(bi); Object o=in.readObject(); return o; } catch (IOException e) { e.printStackTrace(); return null; } catch (ClassNotFoundException e) { e.printStackTrace(); return null; } finally{ try { out.close(); in.close(); } catch (IOException e) { e.printStackTrace(); } } } } class Father implements Serializable{}

结构模式 如何把简单的类根据某种结构组装为大的系统 

6.适配器模式(Adapter)在原类型不做任何改变的情况下,用一个适配器类把一个接口转成另一个接口,扩展了新的接口,灵活且多样的适配一切旧俗。这种打破旧框框,适配新格局的思想,是面向对象的精髓。以继承方式实现的类的 Adapter模式和以聚合方式实现的对象的Adapter模式,各有千秋,各取所长。

[java] view plaincopyprint?
  1. public class TestAdapter  
  2.   
  3. public static void main(String[] args)  
  4.   
  5. USB mouse=new Mouse();  
  6.   
  7. PC pc=new PC();  
  8.   
  9. //pc.useMouse(mouse);   
  10.   
  11. PS2 adapter=new USB2PS2Adapter(mouse);  
  12.   
  13. pc.useMouse(adapter);  
  14.   
  15.  
  16.   
  17.  
  18.   
  19. interface PS2{  
  20.   
  21. void usePs2();  
  22.   
  23.  
  24.   
  25. interface USB{  
  26.   
  27. void useUsb();  
  28.   
  29.  
  30.   
  31. class Mouse implements USB{  
  32.   
  33. public void useUsb(){  
  34.   
  35. System.out.println("通过USB接口工作");  
  36.   
  37.  
  38.   
  39.  
  40.   
  41. class PC{  
  42.   
  43. public void useMouse(PS2 ps2Mouse){  
  44.   
  45. ps2Mouse.usePs2();  
  46.   
  47.  
  48.   
  49.  
  50.   
  51. class USB2PS2Adapter implements PS2{  
  52.   
  53. private USB usb;  
  54.   
  55. public USB2PS2Adapter(USB usb)  
  56.   
  57. this.usb usb;  
  58.   
  59.  
  60.   
  61. public void usePs2(){  
  62.   
  63. System.out.println("把对usePS2的方法调用转换成对useUSB的方法调用");  
  64.   
  65. usb.useUsb();  
  66.   
  67.  
  68.   
  69.   
public class TestAdapter { public static void main(String[] args) { USB mouse=new Mouse(); PC pc=new PC(); //pc.useMouse(mouse); PS2 adapter=new USB2PS2Adapter(mouse); pc.useMouse(adapter); } } interface PS2{ void usePs2(); } interface USB{ void useUsb(); } class Mouse implements USB{ public void useUsb(){ System.out.println("通过USB接口工作"); } } class PC{ public void useMouse(PS2 ps2Mouse){ ps2Mouse.usePs2(); } } class USB2PS2Adapter implements PS2{ private USB usb; public USB2PS2Adapter(USB usb) { this.usb = usb; } public void usePs2(){ System.out.println("把对usePS2的方法调用转换成对useUSB的方法调用"); usb.useUsb(); } }

 

7.组合模式(Composite) 把整体和局部的关系用树状结构描述出来,使得客户端把整体对象和局部对象同等看待。

[java] view plaincopyprint?
  1. import java.util.*;  
  2.   
  3. public class TestComposite  
  4.   
  5. public static void main(String[] args)  
  6.   
  7. Node n1=new LeafNode(3);  
  8.   
  9. Node n2=new LeafNode(4);  
  10.   
  11. Node n3=new LeafNode(6);  
  12.   
  13. Node n4=new LeafNode(5);  
  14.   
  15. Node n5=new LeafNode(2);  
  16.   
  17. Node n6=new LeafNode(9);  
  18.   
  19. Node n7=new LeafNode(12);  
  20.   
  21. Node n8=new LeafNode(7);  
  22.   
  23. Node n9=new LeafNode(8);  
  24.   
  25. Node c1=new CompositeNode(n1,n2,n3);  
  26.   
  27. Node c4=new CompositeNode(n8,n9);  
  28.   
  29. Node c3=new CompositeNode(n5,c4);  
  30.   
  31. Node c2=new CompositeNode(n4,c3);  
  32.   
  33. Node c5=new CompositeNode(n6,n7);  
  34.   
  35. Node root=new CompositeNode(c1,c2,c5);  
  36.   
  37.   
  38.   
  39. System.out.println(root.getValue());  
  40.   
  41.  
  42.   
  43.  
  44.   
  45. abstract class Node{  
  46.   
  47. public abstract int getValue();  
  48.   
  49.  
  50.   
  51. class LeafNode extends Node{  
  52.   
  53. int value;  
  54.   
  55. public LeafNode(int value){  
  56.   
  57. this.value=value;  
  58.   
  59.  
  60.   
  61. public int getValue(){  
  62.   
  63. return value;  
  64.   
  65.  
  66.   
  67.  
  68.   
  69. class CompositeNode extends Node{  
  70.   
  71. private List children=new ArrayList();  
  72.   
  73. public CompositeNode(Node... nodes){  
  74.   
  75. for(Node n:nodes){  
  76.   
  77. children.add(n);  
  78.   
  79.  
  80.   
  81.  
  82.   
  83. public int getValue(){  
  84.   
  85. int result=0 
  86.   
  87. for(Node n:children){  
  88.   
  89. result+=n.getValue();  
  90.   
  91.  
  92.   
  93. return result;  
  94.   
  95.  
  96.   
  97.   
  98.   
  99.   
import java.util.*; public class TestComposite { public static void main(String[] args) { Node n1=new LeafNode(3); Node n2=new LeafNode(4); Node n3=new LeafNode(6); Node n4=new LeafNode(5); Node n5=new LeafNode(2); Node n6=new LeafNode(9); Node n7=new LeafNode(12); Node n8=new LeafNode(7); Node n9=new LeafNode(8); Node c1=new CompositeNode(n1,n2,n3); Node c4=new CompositeNode(n8,n9); Node c3=new CompositeNode(n5,c4); Node c2=new CompositeNode(n4,c3); Node c5=new CompositeNode(n6,n7); Node root=new CompositeNode(c1,c2,c5); System.out.println(root.getValue()); } } abstract class Node{ public abstract int getValue(); } class LeafNode extends Node{ int value; public LeafNode(int value){ this.value=value; } public int getValue(){ return value; } } class CompositeNode extends Node{ private List children=new ArrayList(); public CompositeNode(Node... nodes){ for(Node n:nodes){ children.add(n); } } public int getValue(){ int result=0; for(Node n:children){ result+=n.getValue(); } return result; } }

8.装饰模式(Decorator) 以对客户透明的方式来扩展对象的功能。用户根据功能需求随意选取组成对象的成分,通过方法的链式调用来实现。 可以给对象动态的增加功能,比继承灵活性更大。

[java] view plaincopyprint?
  1. public class TestDecorator  
  2.   
  3. public static void main(String[] args)  
  4.   
  5. Teacher t1=new SimpleTeacher();  
  6.   
  7. Teacher t2=new CppTeacher(t1);  
  8.   
  9. Teacher t3=new JavaTeacher(t2);  
  10.   
  11. t3.teach();  
  12.   
  13. //t.teach();   
  14.   
  15.  
  16.   
  17.  
  18.   
  19.   
  20.   
  21. abstract class Teacher{  
  22.   
  23. public abstract void teach();  
  24.   
  25.  
  26.   
  27. class SimpleTeacher extends Teacher{  
  28.   
  29. public void teach(){  
  30.   
  31. System.out.println("Good Good Study, Day Day Up");  
  32.   
  33.  
  34.   
  35.  
  36.   
  37. class JavaTeacher extends Teacher{  
  38.   
  39. Teacher teacher;  
  40.   
  41. public JavaTeacher(Teacher t){  
  42.   
  43. this.teacher=t;  
  44.   
  45.  
  46.   
  47. public void teach(){  
  48.   
  49. teacher.teach();  
  50.   
  51. System.out.println("Teach Java");  
  52.   
  53.  
  54.   
  55.  
  56.   
  57. class CppTeacher extends Teacher{  
  58.   
  59. Teacher teacher;  
  60.   
  61. public CppTeacher(Teacher t){  
  62.   
  63. this.teacher=t;  
  64.   
  65.  
  66.   
  67. public void teach(){  
  68.   
  69. teacher.teach();  
  70.   
  71. System.out.println("Teach C++");  
  72.   
  73.  
  74.   
  75.   
public class TestDecorator { public static void main(String[] args) { Teacher t1=new SimpleTeacher(); Teacher t2=new CppTeacher(t1); Teacher t3=new JavaTeacher(t2); t3.teach(); //t.teach(); } } abstract class Teacher{ public abstract void teach(); } class SimpleTeacher extends Teacher{ public void teach(){ System.out.println("Good Good Study, Day Day Up"); } } class JavaTeacher extends Teacher{ Teacher teacher; public JavaTeacher(Teacher t){ this.teacher=t; } public void teach(){ teacher.teach(); System.out.println("Teach Java"); } } class CppTeacher extends Teacher{ Teacher teacher; public CppTeacher(Teacher t){ this.teacher=t; } public void teach(){ teacher.teach(); System.out.println("Teach C++"); } }

9.代理模式(Proxy) 用一个代理对象来作为另一个对象的代理,对客户来说是透明的。存在一个抽象主题类,具体主题类和代理主题类都继承(实现)抽象主题,代理主题类中的方法会调用具体主题类中相对应的方法。

10.享元模式(Flyweight Pattern)对象的状态分为内蕴状态和外蕴状态。内蕴状态不随环境变化而变化,因此可以作成系统共享. 

11.门面模式(Facade) 访问子系统的时候,通过一个Façade对象访问。Facade类是单例的。客户代码只需要和门面对象通信,不需要和具体子系统内部的对象通信,使得他们之间的耦合关系减弱。这次将表现层和逻辑层隔离,封装底层的复杂处理,为用户提供简单的接口,这样的例子随处可见。

门面模式很多时候更是一种系统架构的设计,在我所做的项目中,就实现了门面模式的接口,为复杂系统的解耦提供了最好的解决方案。 

12.桥梁模式(Bridge)将抽象和实现脱耦,使得二者可以单独变化。使得一个继承关系不承担两个变化因素.使用合成来代替继承的一种体现.

[java] view plaincopyprint?
  1. public YuanUser(BankAccount account)  
  2.   
  3. super(account);  
  4.   
  5.   
  6.   
  7.  
  8.   
  9. public void getMoney()  
  10.   
  11. System.out.print("人民币");  
  12.   
  13. account.withdraw();  
  14.   
  15.  
  16.   
  17. public void saveMoney()  
  18.   
  19. System.out.print("人民币");  
  20.   
  21. account.deposit();  
  22.   
  23.  
  24.   
  25.   
  26.   
  27.  
  28.   
  29. class DollarUser extends BankUser{  
  30.   
  31.   
  32.   
  33. public DollarUser(BankAccount account)  
  34.   
  35. super(account);  
  36.   
  37.   
  38.   
  39.  
  40.   
  41. public void getMoney()  
  42.   
  43. System.out.print("美元");  
  44.   
  45. account.withdraw();  
  46.   
  47.  
  48.   
  49. public void saveMoney()  
  50.   
  51. System.out.print("美元");  
  52.   
  53. account.deposit();  
  54.   
  55.  
  56.   
  57.   
public YuanUser(BankAccount account) { super(account); } public void getMoney() { System.out.print("人民币"); account.withdraw(); } public void saveMoney() { System.out.print("人民币"); account.deposit(); } } class DollarUser extends BankUser{ public DollarUser(BankAccount account) { super(account); } public void getMoney() { System.out.print("美元"); account.withdraw(); } public void saveMoney() { System.out.print("美元"); account.deposit(); } }
 

行为模式 描述如何在对象之间划分责任 

13.策略模式(Strategy)如同LayoutManager和具体的布局管理器的关系,在抽象策略类中定义方法,将易于变化的部分封装为接口,通常Strategy 封装一些运算法则,使之能互换。Bruce Zhang在他的博客中提到策略模式其实是一种“面向接口”的编程方法,真是恰如其分。在具体策略子类中实现,客户代码根据不同的需要选择相应的具体类,例如电子商务中多种价格算法。一种策略一旦选中,整个系统运行期是不变化的

[java] view plaincopyprint?
  1. public class TestStrategy  
  2.   
  3. public static void main(String[] args)  
  4.   
  5. Strategy s1=new May1Strategy();  
  6.   
  7. Strategy s2=new June1Strategy();  
  8.   
  9. Book b=new Book(100);  
  10.   
  11. b.setS(s2);  
  12.   
  13.   
  14.   
  15. System.out.println(b.getPrice());  
  16.   
  17.   
  18.   
  19.  
  20.   
  21.  
  22.   
  23.   
  24.   
  25. class Book{  
  26.   
  27. Strategy s;  
  28.   
  29. public Book(double price){  
  30.   
  31. this.price=price;  
  32.   
  33.  
  34.   
  35. private double price;  
  36.   
  37.   
  38.   
  39. public void setS(Strategy s)  
  40.   
  41. this.s s;  
  42.   
  43.  
  44.   
  45.   
  46.   
  47. public double getPrice(){  
  48.   
  49. return price*s.getZheKou();  
  50.   
  51.  
  52.   
  53.   
  54.   
  55.  
  56.   
  57.   
  58.   
  59. interface Strategy{  
  60.   
  61. double getZheKou();  
  62.   
  63.  
  64.   
  65. class May1Strategy implements Strategy{  
  66.   
  67. public double getZheKou(){  
  68.   
  69. return 0.8 
  70.   
  71.  
  72.   
  73.  
  74.   
  75. class June1Strategy implements Strategy{  
  76.   
  77. public double getZheKou(){  
  78.   
  79. return 0.7 
  80.   
  81.  
  82.   
  83.   
public class TestStrategy { public static void main(String[] args) { Strategy s1=new May1Strategy(); Strategy s2=new June1Strategy(); Book b=new Book(100); b.setS(s2); System.out.println(b.getPrice()); } } class Book{ Strategy s; public Book(double price){ this.price=price; } private double price; public void setS(Strategy s) { this.s = s; } public double getPrice(){ return price*s.getZheKou(); } } interface Strategy{ double getZheKou(); } class May1Strategy implements Strategy{ public double getZheKou(){ return 0.8; } } class June1Strategy implements Strategy{ public double getZheKou(){ return 0.7; } }
14.模板方法(Template Method)准备一个抽象类,把部分确定的逻辑定义在某些方法中,用其他抽象方法实现剩余的逻辑。不同子类对这些逻辑有不同的实现。用法:定义多个抽象操作,定义并实现一个模板方法,将步骤放在这个具体方法里,推迟到子类实现。子类可以改变父类的可变部分,但不能改变模板方法所代表的顶级逻辑。
[java] view plaincopyprint?
  1. public class TestTemplateMethod  
  2.   
  3. public static void main(String[] args)  
  4.   
  5. XiaoPin xp=new DaPuKe();  
  6.   
  7. xp.act();  
  8.   
  9.  
  10.   
  11.  
  12.   
  13. abstract class XiaoPin{  
  14.   
  15. public abstract void jiaoLiu();  
  16.   
  17. public abstract void xuShi();  
  18.   
  19. public abstract void gaoXiao();  
  20.   
  21. public abstract void shanQing();  
  22.   
  23. public final void act(){  
  24.   
  25. jiaoLiu();  
  26.   
  27. xuShi();  
  28.   
  29. gaoXiao();  
  30.   
  31. shanQing();  
  32.   
  33.  
  34.   
  35.  
  36.   
  37. class DaPuKe extends XiaoPin{  
  38.   
  39. public void jiaoLiu(){  
  40.   
  41. System.out.println("顺口溜");  
  42.   
  43.  
  44.   
  45. public void xuShi(){  
  46.   
  47. System.out.println("火车除夕,老同学见面");  
  48.   
  49.  
  50.   
  51. public void gaoXiao(){  
  52.   
  53. System.out.println("名片当作扑克");  
  54.   
  55.  
  56.   
  57. public void shanQing(){  
  58.   
  59. System.out.println("马家军");  
  60.   
  61.  
  62.   
  63.   
public class TestTemplateMethod { public static void main(String[] args) { XiaoPin xp=new DaPuKe(); xp.act(); } } abstract class XiaoPin{ public abstract void jiaoLiu(); public abstract void xuShi(); public abstract void gaoXiao(); public abstract void shanQing(); public final void act(){ jiaoLiu(); xuShi(); gaoXiao(); shanQing(); } } class DaPuKe extends XiaoPin{ public void jiaoLiu(){ System.out.println("顺口溜"); } public void xuShi(){ System.out.println("火车除夕,老同学见面"); } public void gaoXiao(){ System.out.println("名片当作扑克"); } public void shanQing(){ System.out.println("马家军"); } }
 

 

15.观察者模式(Observer) 定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时, 所有依赖于它的对象都得到通知并被自动更新。观察者和被观察者的分开,为模块划分提供了清晰的界限。在低耦合的对象间完成协调。 Java中的事件模型就是一个应用。

16.迭代器模式(Iterator)类似于集合中的Iterator,使用迭代器来统一不同集合对象的遍历方式。在绝大多数的系统中,都会用到数组、集合、链表、队列这样的类型,关心迭代模式的来龙去脉非常有必要。在遍历算法中,迭代模式提供了遍历的顺序访问容器,GOF给出的定义为:提供一种方法访问一个容器(container)对象中各个元素,而又不需暴露该对象的内部细节。.NET中就是使用了迭代器来创建用于foreach的集合。

[java] view plaincopyprint?
  1. public class TestIterator  
  2.   
  3. public static void main(String[] args)  
  4.   
  5. Stack s=new Stack();  
  6.   
  7. s.push("Liucy");  
  8.   
  9. s.push("Huxz");  
  10.   
  11. s.push("George");  
  12.   
  13.   
  14.   
  15. LinkedList l=new LinkedList();  
  16.   
  17. l.addFirst("Liucy");  
  18.   
  19. l.addFirst("Huxz");  
  20.   
  21. l.addFirst("George");  
  22.   
  23.   
  24.   
  25. print(l.iterator());  
  26.   
  27.  
  28.   
  29.   
  30.   
  31. public static void print(Itr it){  
  32.   
  33. while(it.hasNext()){  
  34.   
  35. System.out.println(it.next());  
  36.   
  37.  
  38.   
  39.  
  40.   
  41.  
  42.   
  43. interface Itr{  
  44.   
  45. boolean hasNext();  
  46.   
  47. Object next();  
  48.   
  49.  
  50.   
  51. class Stack{  
  52.   
  53. Object[] os=new Object[10];  
  54.   
  55. int index=0 
  56.   
  57. private void expand(){  
  58.   
  59. Object[] os2=new Object[os.length*2];  
  60.   
  61. System.arraycopy(os,0,os2,0,os.length);  
  62.   
  63. os=os2;  
  64.   
  65.  
  66.   
  67. public void push(Object o){  
  68.   
  69. if (index==os.length) expand();  
  70.   
  71. os[index]=o;  
  72.   
  73. index++;  
  74.   
  75.  
  76.   
  77. public Object pop(){  
  78.   
  79. index--;  
  80.   
  81. Object o=os[index];  
  82.   
  83. os[index]=null 
  84.   
  85. return o;  
  86.   
  87.  
  88.   
  89. private class StackItr implements Itr{  
  90.   
  91. int cursor=0 
  92.   
  93. public boolean hasNext(){  
  1. return cursor}  
  2.   
  3. public Object next(){  
  4.   
  5. return os[cursor++];  
  6.   
  7.  
  8.   
  9.  
  10.   
  11. public Itr iterator(){  
  12.   
  13. return new StackItr();  
  14.   
  15.  
  16.   
  17.  
  18.   
  19.   
  20.   
  21. class LinkedList{  
  22.   
  23. private class Node{  
  24.   
  25. Object o;  
  26.   
  27. Node next;  
  28.   
  29. public Node(Object o){  
  30.   
  31. this.o=o;  
  32.   
  33.  
  34.   
  35. public void setNext(Node next){  
  36.   
  37. this.next=next;  
  38.   
  39.  
  40.   
  41. public Node getNext(){  
  42.   
  43. return this.next;  
  44.   
  45.  
  46.   
  47.  
  48.   
  49.   
  50.   
  51. Node head;  
  52.   
  53. public void addFirst(Object o){  
  54.   
  55. Node n=new Node(o);  
  56.   
  57. n.setNext(head);  
  58.   
  59. head=n;  
  60.   
  61.  
  62.   
  63. public Object removeFirst(){  
  64.   
  65. Node n=head;  
  66.   
  67. head=head.getNext();  
  68.   
  69. return n.o;  
  70.   
  71.  
  72.   
  73.   
  74.   
  75. class LinkedListItr implements Itr{  
  76.   
  77. Node currentNode=head;  
  78.   
  79. public boolean hasNext(){  
  80.   
  81. return this.currentNode!=null 
  82.   
  83.  
  84.   
  85. public Object next(){  
  86.   
  87. Node n=currentNode;  
  88.   
  89. currentNode=currentNode.getNext();  
  90.   
  91. return n.o;  
  92.   
  93.  
  94.   
  95.  
  96.   
  97. public Itr iterator(){  
  98.   
  99. return new LinkedListItr();  
  100.   
  101.  
  102.   
  103.   
public class TestIterator { public static void main(String[] args) { Stack s=new Stack(); s.push("Liucy"); s.push("Huxz"); s.push("George"); LinkedList l=new LinkedList(); l.addFirst("Liucy"); l.addFirst("Huxz"); l.addFirst("George"); print(l.iterator()); } public static void print(Itr it){ while(it.hasNext()){ System.out.println(it.next()); } } } interface Itr{ boolean hasNext(); Object next(); } class Stack{ Object[] os=new Object[10]; int index=0; private void expand(){ Object[] os2=new Object[os.length*2]; System.arraycopy(os,0,os2,0,os.length); os=os2; } public void push(Object o){ if (index==os.length) expand(); os[index]=o; index++; } public Object pop(){ index--; Object o=os[index]; os[index]=null; return o; } private class StackItr implements Itr{ int cursor=0; public boolean hasNext(){ return cursor} public Object next(){ return os[cursor++]; } } public Itr iterator(){ return new StackItr(); } } class LinkedList{ private class Node{ Object o; Node next; public Node(Object o){ this.o=o; } public void setNext(Node next){ this.next=next; } public Node getNext(){ return this.next; } } Node head; public void addFirst(Object o){ Node n=new Node(o); n.setNext(head); head=n; } public Object removeFirst(){ Node n=head; head=head.getNext(); return n.o; } class LinkedListItr implements Itr{ Node currentNode=head; public boolean hasNext(){ return this.currentNode!=null; } public Object next(){ Node n=currentNode; currentNode=currentNode.getNext(); return n.o; } } public Itr iterator(){ return new LinkedListItr(); } }

 

17.责任链(Chain of Responsibility)多个处理器对象连成一串,请求在这条链上传递,由该处理这个请求的处理器来处理。发出请求的客户端并不知道哪个对象处理请求。

[java] view plaincopyprint?
  1. public class TestChain  
  2.   
  3. public static void main(String[] args)  
  4.   
  5. String pass1="123456" 
  6.   
  7. String pass2="123456" 
  8.   
  9. String personId="123456789012345678" 
  10.   
  11. String email="chmask@163.com" 
  12.   
  13.   
  14.   
  15. register(pass1,pass2,personId,email);  
  16.   
  17.   
  18.   
  19.  
  20.   
  21. public static void register(String pass1,String pass2,String personId,String email){  
  22.   
  23. Filter f1=new PasswordFilter1();  
  24.   
  25. Filter f2=new PasswordFilter2();  
  26.   
  27. Filter f3=new PersonIdFilter();  
  28.   
  29. Filter f4=new EmailFilter();  
  30.   
  31.   
  32.   
  33. f1.setNext(f2);  
  34.   
  35. f2.setNext(f3);  
  36.   
  37. f3.setNext(f4);  
  38.   
  39.   
  40.   
  41. System.out.println(f1.doFilter(pass1,pass2,personId,email));  
  42.   
  43.  
  44.   
  45.  
  46.   
  47. abstract class Filter{  
  48.   
  49. Filter next=null 
  50.   
  51. public Filter getNext()  
  52.   
  53. return next;  
  54.   
  55.  
  56.   
  57. public void setNext(Filter next)  
  58.   
  59. this.next next;  
  60.   
  61.  
  62.   
  63. public String doFilter(String pass1,String pass2,String personId,String email){  
  64.   
  65. if (next==nullreturn "成功" 
  66.   
  67. else return next.doFilter(pass1,pass2,personId,email);  
  68.   
  69.  
  70.   
  71.  
  72.   
  73. class PasswordFilter1 extends Filter{  
  74.   
  75. public String doFilter(String pass1,String pass2,String personId,String email){  
  76.   
  77. if (!(pass1.equals(pass2)))  
  78.   
  79. return "两次密码输入不一致" 
  80.   
  81. else return super.doFilter(pass1,pass2,personId,email);  
  82.   
  83.  
  84.   
  85.  
  86.   
  87. class PasswordFilter2 extends Filter{  
  88.   
  89. public String doFilter(String pass1,String pass2,String personId,String email){  
  90.   
  91. if (pass1.length()!=6 
  92.   
  93. return "密码长度必须为6" 
  94.   
  95. else return super.doFilter(pass1,pass2,personId,email);  
  96.   
  97.  
  98.   
  99.  
  100.   
  101. class PersonIdFilter extends Filter{  
  102.   
  103. public String doFilter(String pass1,String pass2,String personId,String email){  
  104.   
  105. if (personId.length()!=15 && personId.length()!=18 
  106.   
  107. return "身份证号码非法" 
  108.   
  109. else return super.doFilter(pass1,pass2,personId,email);  
  110.   
  111.  
  112.   
  113.  
  114.   
  115. class EmailFilter extends Filter{  
  116.   
  117. public String doFilter(String pass1,String pass2,String personId,String email){  
  118.   
  119. int i1=email.indexOf("@");  
  120.   
  121. int i2=email.indexOf(".");  
  122.   
  123. if (i1==-1 || i2==-1 || i2-i1<=1 || i1==0 || i2==email.length()-1 
  124.   
  125. return "email非法" 
  126.   
  127. else return super.doFilter(pass1,pass2,personId,email);  
  128.   
  129.  
  130.   
  131.   
public class TestChain { public static void main(String[] args) { String pass1="123456"; String pass2="123456"; String personId="123456789012345678"; String email="chmask@163.com"; register(pass1,pass2,personId,email); } public static void register(String pass1,String pass2,String personId,String email){ Filter f1=new PasswordFilter1(); Filter f2=new PasswordFilter2(); Filter f3=new PersonIdFilter(); Filter f4=new EmailFilter(); f1.setNext(f2); f2.setNext(f3); f3.setNext(f4); System.out.println(f1.doFilter(pass1,pass2,personId,email)); } } abstract class Filter{ Filter next=null; public Filter getNext() { return next; } public void setNext(Filter next) { this.next = next; } public String doFilter(String pass1,String pass2,String personId,String email){ if (next==null) return "成功"; else return next.doFilter(pass1,pass2,personId,email); } } class PasswordFilter1 extends Filter{ public String doFilter(String pass1,String pass2,String personId,String email){ if (!(pass1.equals(pass2))) return "两次密码输入不一致"; else return super.doFilter(pass1,pass2,personId,email); } } class PasswordFilter2 extends Filter{ public String doFilter(String pass1,String pass2,String personId,String email){ if (pass1.length()!=6) return "密码长度必须为6"; else return super.doFilter(pass1,pass2,personId,email); } } class PersonIdFilter extends Filter{ public String doFilter(String pass1,String pass2,String personId,String email){ if (personId.length()!=15 && personId.length()!=18) return "身份证号码非法"; else return super.doFilter(pass1,pass2,personId,email); } } class EmailFilter extends Filter{ public String doFilter(String pass1,String pass2,String personId,String email){ int i1=email.indexOf("@"); int i2=email.indexOf("."); if (i1==-1 || i2==-1 || i2-i1<=1 || i1==0 || i2==email.length()-1) return "email非法"; else return super.doFilter(pass1,pass2,personId,email); } }

18.状态模式(State) 在对象内部状态改变时改变其行为。把所研究的对象的行为封装在不同的状态对象中。

[java] view plaincopyprint?
  1. import static java.lang.System.*;  
  2.   
  3. public class TestState  
  4.   
  5. public static void main(String[] args)  
  6.   
  7. BBSUser u=new BBSUser();  
  8.   
  9. u.setState(new GuestState());  
  10.   
  11. u.publish();  
  12.   
  13.   
  14.   
  15. u.setState(new NormalState());  
  16.   
  17. u.publish();  
  18.   
  19.   
  20.   
  21. u.setState(new BlockedState());  
  22.   
  23. u.publish();  
  24.   
  25.   
  26.   
  27. u.setState(new NewComerState());  
  28.   
  29. u.publish();  
  30.   
  31.  
  32.   
  33.  
  34.   
  35. class BBSUser{  
  36.   
  37. private State state;  
  38.   
  39. public void setState(State state){  
  40.   
  41. this.state=state;  
  42.   
  43.  
  44.   
  45. public void publish(){  
  46.   
  47. state.action();  
  48.   
  49.  
  50.   
  51.  
  52.   
  53. abstract class State{  
  54.   
  55. public abstract void action();  
  56.   
  57.  
  58.   
  59. class GuestState extends State{  
  60.   
  61. public void action(){  
  62.   
  63. out.println("您处在游客状态,请先登录");  
  64.   
  65.  
  66.   
  67.  
  68.   
  69. class NormalState extends State{  
  70.   
  71. public void action(){  
  72.   
  73. out.println("您处在正常状态,文章发表成功");  
  74.   
  75.  
  76.   
  77.  
  78.   
  79. class BlockedState extends State{  
  80.   
  81. public void action(){  
  82.   
  83. out.println("您处在被封状态,文章发表失败");  
  84.   
  85.  
  86.   
  87.  
  88.   
  89. class NewComerState extends State{  
  90.   
  91. public void action(){  
  92.   
  93. out.println("您是新手,请先学习一下,3天后再来");  
  94.   
  95.  
  96.   
  97.  
  98.   
  99.   
  100.   
  101. class StateFactory{  
  102.   
  103. public static State createState(int i){  
  104.   
  105. if (i==1return new GuestState();  
  106.   
  107. else return new NormalState();  
  108.   
  109.  
  110.   
  111.   
import static java.lang.System.*; public class TestState { public static void main(String[] args) { BBSUser u=new BBSUser(); u.setState(new GuestState()); u.publish(); u.setState(new NormalState()); u.publish(); u.setState(new BlockedState()); u.publish(); u.setState(new NewComerState()); u.publish(); } } class BBSUser{ private State state; public void setState(State state){ this.state=state; } public void publish(){ state.action(); } } abstract class State{ public abstract void action(); } class GuestState extends State{ public void action(){ out.println("您处在游客状态,请先登录"); } } class NormalState extends State{ public void action(){ out.println("您处在正常状态,文章发表成功"); } } class BlockedState extends State{ public void action(){ out.println("您处在被封状态,文章发表失败"); } } class NewComerState extends State{ public void action(){ out.println("您是新手,请先学习一下,3天后再来"); } } class StateFactory{ public static State createState(int i){ if (i==1) return new GuestState(); else return new NormalState(); } }

19.备忘录模式(Memento) 备忘录对象用来存储另一个对象的快照对象,保存其内部状态,使得可以随时恢复。备忘录角色:保存发起人对象的内部状态,保护内容不被除发起人对象之外的对象获取。窄接口:负责人对象和其他对象看到的接口,只允许把备忘录对象传给其他对象。宽接口:发起人能看到的接口,允许读取内部状态。发起人角色:创建并使用备忘录对象来保存其状态 负责人角色:负责保存备忘录对象。 白箱实现:备忘录类对其他类也可见,这样发起人的状态可能会存在安全问题。 黑箱实现:把备忘录类作成发起人的内部类,对外提供一个标识接口。

[java] view plaincopyprint?
  1. public class TestMemento{  
  2.   
  3. public static void main(String[] args){  
  4.   
  5. Originator ori=new Originator();  
  6.   
  7. Caretaker c=new Caretaker();  
  8.   
  9. ori.setState("State 1");  
  10.   
  11. IFMemento m=ori.createMemento();  
  12.   
  13. c.save(m);  
  14.   
  15. ori.setState("State 2");  
  16.   
  17. m=c.retrieve();  
  18.   
  19. ori.restore(m);  
  20.   
  21. System.out.println("Now State:"+ori.getState());  
  22.   
  23.   
  24.   
  25.  
  26.   
  27.  
  28.   
  29. class Originator{  
  30.   
  31. String state;  
  32.   
  33. public void setState(String s){  
  34.   
  35. state=s;  
  36.   
  37. System.out.println("State change to: "+s);  
  38.   
  39.  
  40.   
  41. public String getState(){  
  42.   
  43. return this.state;  
  44.   
  45.  
  46.   
  47. public IFMemento createMemento(){  
  48.   
  49. return new Memento(state);  
  50.   
  51.  
  52.   
  53. public void restore(IFMemento m){  
  54.   
  55. Memento mt=(Memento)m;  
  56.   
  57. this.state=mt.getState();  
  58.   
  59.  
  60.   
  61. private class Memento implements IFMemento{  
  62.   
  63. private String state;  
  64.   
  65. public Memento(String s){  
  66.   
  67. this.state=s;  
  68.   
  69.  
  70.   
  71. public String getState(){  
  72.   
  73. return this.state;  
  74.   
  75.  
  76.   
  77.  
  78.   
  79.  
  80.   
  81.   
  82.   
  83. class Caretaker{  
  84.   
  85. private IFMemento m;  
  86.   
  87. public IFMemento retrieve(){  
  88.   
  89. return this.m;  
  90.   
  91.  
  92.   
  93. public void save(IFMemento m){  
  94.   
  95. this.m=m;  
  96.   
  97.  
  98.   
  99.  
  100.   
  101.   
  102.   
  103. interface IFMemento{  
  104.   
  105.   
  106.   
  107.  

 

  1.   
原创粉丝点击