Java 設計模式

創建模式

1.工廠方法模式(Factory Method)  將程序中創建對象的操作,單獨出來處理,創建一個產品的工廠接口,把實際的工作轉移到具體的子類。大大提高了系統擴展的柔性,接口的抽象化處理給相互依賴的對象創建提供了最好的抽象模式。

[java] view plaincopy
  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. }   

 

2.抽象工廠模式(Abstract Factory) 針對多個產品等級的情況,而工廠方法模式針對單一產品等級的情況。
[java] view plaincopy
  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. }   
3.單例模式(Singleton) 改善全局變量和命名空間的衝突,可以說是一種改良了的全局變量。這種一個類只有一個實例,且提供一個訪問全局點的方式,更加靈活的保證了實例的創建和訪問約束。系統中只有一個實例,因此構造方法應該爲私有 餓漢式:類加載時直接創建靜態實例 懶漢式:第一次需要時才創建一個實例,那麼newInstance方法要加同步 餓漢式比懶漢式要好,儘管資源利用率要差。但是不用同步。
[java] view plaincopy
  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==null) i=new ClassB();  
  32.   
  33. return i;  
  34.   
  35. }  
  36.   
  37. private ClassB(){}  
  38.   
  39. }   

4.建造模式(Builder) 將一個對象的內部表象和建造過程分割,一個建造過程可以造出不同表象的對象。可簡化爲模版方法模式.

[java] view plaincopy
  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{}   

5.原型模式(ProtoType) 通過一個原型對象來創建一個新對象(克隆)。Java中要給出Clonable接口的實現,具體類要實現這個接口,並給出clone()方法的實現細節,這就是簡單原型模式的應用。  淺拷貝:只拷貝簡單屬性的值和對象屬性的地址  深拷貝:拷貝本對象引用的對象,有可能會出現循環引用的情況。可以用串行化解決深拷貝。寫到流裏再讀出來,這時會是一個對象的深拷貝結果。

[java] view plaincopy
  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{}  

結構模式 如何把簡單的類根據某種結構組裝爲大的系統 

6.適配器模式(Adapter) 在原類型不做任何改變的情況下,用一個適配器類把一個接口轉成另一個接口,擴展了新的接口,靈活且多樣的適配一切舊俗。這種打破舊框框,適配新格局的思想,是面向對象的精髓。以繼承方式實現的類的 Adapter模式和以聚合方式實現的對象的Adapter模式,各有千秋,各取所長。

[java] view plaincopy
  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. }   

 

7.組合模式(Composite) 把整體和局部的關係用樹狀結構描述出來,使得客戶端把整體對象和局部對象同等看待。

[java] view plaincopy
  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. }   

8.裝飾模式(Decorator) 以對客戶透明的方式來擴展對象的功能。 用戶根據功能需求隨意選取組成對象的成分,通過方法的鏈式調用來實現。 可以給對象動態的增加功能,比繼承靈活性更大。

[java] view plaincopy
  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. }   

9.代理模式(Proxy) 用一個代理對象來作爲另一個對象的代理,對客戶來說是透明的。 存在一個抽象主題類,具體主題類和代理主題類都繼承(實現)抽象主題,代理主題類中的方法會調用具體主題類中相對應的方法。

10.享元模式(Flyweight Pattern) 對象的狀態分爲內蘊狀態和外蘊狀態。內蘊狀態不隨環境變化而變化,因此可以作成系統共享. 

11.門面模式(Facade) 訪問子系統的時候,通過一個Façade對象訪問。Facade類是單例的。 客戶代碼只需要和門面對象通信,不需要和具體子系統內部的對象通信,使得他們之間的耦合關係減弱。 這次將表現層和邏輯層隔離,封裝底層的複雜處理,爲用戶提供簡單的接口,這樣的例子隨處可見。

門面模式很多時候更是一種系統架構的設計,在我所做的項目中,就實現了門面模式的接口,爲複雜系統的解耦提供了最好的解決方案。 

12.橋樑模式(Bridge) 將抽象和實現脫耦,使得二者可以單獨變化。使得一個繼承關係不承擔兩個變化因素.使用合成來代替繼承的一種體現.

[java] view plaincopy
  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. }   
 

行爲模式 描述如何在對象之間劃分責任 

13.策略模式(Strategy) 如同LayoutManager和具體的佈局管理器的關係,在抽象策略類中定義方法,將易於變化的部分封裝爲接口,通常Strategy 封裝一些運算法則,使之能互換。Bruce Zhang在他的博客中提到策略模式其實是一種“面向接口”的編程方法,真是恰如其分。 在具體策略子類中實現,客戶代碼根據不同的需要選擇相應的具體類,例如電子商務中多種價格算法。 一種策略一旦選中,整個系統運行期是不變化的

[java] view plaincopy
  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. }   
14.模板方法(Template Method) 準備一個抽象類,把部分確定的邏輯定義在某些方法中,用其他抽象方法實現剩餘的邏輯。不同子類對這些邏輯有不同的實現。 用法:定義多個抽象操作,定義並實現一個模板方法,將步驟放在這個具體方法裏,推遲到子類實現。子類可以改變父類的可變部分,但不能改變模板方法所代表的頂級邏輯。
[java] view plaincopy
  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. }   
 

 

15.觀察者模式(Observer) 定義對象間的一種一對多的依賴關係,當一個對象的狀態發生改變時, 所有依賴於它的對象都得到通知並被自動更新。觀察者和被觀察者的分開,爲模塊劃分提供了清晰的界限。在低耦合的對象間完成協調。 Java中的事件模型就是一個應用。

16.迭代器模式(Iterator) 類似於集合中的Iterator,使用迭代器來統一不同集合對象的遍歷方式。在絕大多數的系統中,都會用到數組、集合、鏈表、隊列這樣的類型,關心迭代模式的來龍去脈非常有必要。在遍歷算法中,迭代模式提供了遍歷的順序訪問容 器,GOF給出的定義爲:提供一種方法訪問一個容器(container)對象中各個元素,而又不需暴露該對象的內部細節。.NET中就是使用了迭代器來 創建用於foreach的集合。

[java] view plaincopy
  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(){  
  94.   
  95. return cursor}  
  96.   
  97. public Object next(){  
  98.   
  99. return os[cursor++];  
  100.   
  101. }  
  102.   
  103. }  
  104.   
  105. public Itr iterator(){  
  106.   
  107. return new StackItr();  
  108.   
  109. }  
  110.   
  111. }  
  112.   
  113.   
  114.   
  115. class LinkedList{  
  116.   
  117. private class Node{  
  118.   
  119. Object o;  
  120.   
  121. Node next;  
  122.   
  123. public Node(Object o){  
  124.   
  125. this.o=o;  
  126.   
  127. }  
  128.   
  129. public void setNext(Node next){  
  130.   
  131. this.next=next;  
  132.   
  133. }  
  134.   
  135. public Node getNext(){  
  136.   
  137. return this.next;  
  138.   
  139. }  
  140.   
  141. }  
  142.   
  143.   
  144.   
  145. Node head;  
  146.   
  147. public void addFirst(Object o){  
  148.   
  149. Node n=new Node(o);  
  150.   
  151. n.setNext(head);  
  152.   
  153. head=n;  
  154.   
  155. }  
  156.   
  157. public Object removeFirst(){  
  158.   
  159. Node n=head;  
  160.   
  161. head=head.getNext();  
  162.   
  163. return n.o;  
  164.   
  165. }  
  166.   
  167.   
  168.   
  169. class LinkedListItr implements Itr{  
  170.   
  171. Node currentNode=head;  
  172.   
  173. public boolean hasNext(){  
  174.   
  175. return this.currentNode!=null;  
  176.   
  177. }  
  178.   
  179. public Object next(){  
  180.   
  181. Node n=currentNode;  
  182.   
  183. currentNode=currentNode.getNext();  
  184.   
  185. return n.o;  
  186.   
  187. }  
  188.   
  189. }  
  190.   
  191. public Itr iterator(){  
  192.   
  193. return new LinkedListItr();  
  194.   
  195. }  
  196.   
  197. }   

 

17.責任鏈(Chain of Responsibility) 多個處理器對象連成一串,請求在這條鏈上傳遞,由該處理這個請求的處理器來處理。發出請求的客戶端並不知道哪個對象處理請求。

[java] view plaincopy
  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="[email protected]";  
  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. }   

18.狀態模式(State) 在對象內部狀態改變時改變其行爲。把所研究的對象的行爲封裝在不同的狀態對象中。

[java] view plaincopy
  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. }   

19.備忘錄模式(Memento) 備忘錄對象用來存儲另一個對象的快照對象,保存其內部狀態,使得可以隨時恢復。 備忘錄角色:保存發起人對象的內部狀態,保護內容不被除發起人對象之外的對象獲取。窄接口:負責人對象和其他對象看到的接口,只允許把備忘錄對象傳給其他對象。寬接口:發起人能看到的接口,允許讀取內部狀態。 發起人角色:創建並使用備忘錄對象來保存其狀態 負責人角色:負責保存備忘錄對象。  白箱實現:備忘錄類對其他類也可見,這樣發起人的狀態可能會存在安全問題。  黑箱實現:把備忘錄類作成發起人的內部類,對外提供一個標識接口。

[java] view plaincopy
  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. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章