大魚

          23種設計模式的代碼

          java代碼: 


          package lq.test;

          import java.io.*;
          import java.util.*;

          //*********創建型模式***************

          //factory method 1
          //1具體的構造算法,和2構造出的具體產品由子類實現       
          interface Product {
          }

          //或者我也提供一個工廠的接口,由這個抽象類來繼承它

          abstract class Factory {
                  abstract public Product fmd();
                 
                  //我認為這個方方法的存在是,是對FactoryMethod方法的補充
                  //例如可以為生成的對象賦值,計算為生成對象應付何值,前后的日值
                  //且這些都是公用μ模?生成產品的最主要算法還是在FactoryMethod中,
                  //這個方法只是起?ㄖ÷用,這也是一種思維方法,將具體的算法實現在一個方法中
                  //而我2恢±接調用此方法,而使用另外的一個方法封裝它,等到了更靈活的效果,而
                  //子類需實現的內容是FactoryMethod
                  //此方法是一個TemplateMethod
                  public Product creat() {
                          Product pd = null;
                         
                          System.out.println("before operation");
                         
                          pd = fmd();
                         
                          System.out.println("end operation");
                 
                          return pd;
                  }
          }

          class Product1 implements Product {
          }

          class Factory1 extends Factory {
                  public Product fmd() {
                          Product pd = new Product1();
                          return pd;
                  }
          }

          //FactroyMethod 2
          //這種方式簡單實用
          interface Producta {
          }

          interface Factorya {
                  Producta create();
          }

          class Producta1 implements Producta {}

          class Factorya1 implements Factorya {
                  public Producta create() {
                          Producta pda = null;
                          pda = new Producta1();
                          return pda;
                  }
          }

          //AbstractFactory
          //AbstractFactory與FactoryMethod的不同在于AbstractFactory創建多個產品
          //感覺此模式沒有什?創笥?

          //當然可以還有更多的接口
          interface Apda {}

          interface Apdb {}

          interface Afactory {
                  Apda createA();
                  Apdb createB();
          }

          class Apda1 implements Apda {}

          class Apdb1 implements Apdb {}

          //有幾個接口就有幾個對應的方法
          class Afactory1 implements Afactory {
                  public Apda createA() {
                          Apda apda = null;
                          apda = new Apda1();
                          return apda;
                  }
                 
                  public Apdb createB() {
                          Apdb apdb = null;
                          apdb = new Apdb1();
                          return apdb;               
                  }
          }

          //Builder
          //一個產品的生成分為生成部件和組裝部件,不同的產品每個部件生成的方式不同
          //而組裝的方式相同,部件的生成抽象成接口方法,而組裝的方法使用一個TemplateMethod方法

          interface Cpda {}

          class Cpda1 implements Cpda {}

          interface BuilderI {
                  void buildPart1();
                  void buildPart2();
                 
                  void initPd();
                  Cpda getPd();
          }

          abstract class BuilderA implements BuilderI {
                  Cpda cpda;
                 
                  public Cpda getPd() {
                          initPd();
                         
                          //對對象的內容進行設置
                          buildPart1();
                          buildPart2();
                         
                          return cpda;
                  }
          }

          class Builder extends BuilderA {
                  public void buildPart1() {
                          System.out.println(cpda);
                  }
                 
                  public void buildPart2() {
                          System.out.println(cpda);
                  }
                 
                  public void initPd() {
                          cpda = new Cpda1();
                  }       
          }

          //一個簡單的生成產品的實現
          //1
          abstract class Fy {
                  public abstract void med1();
                 
                  static class Fy1 extends Fy {
                          public void med1() {
                          }
                  }
                 
                  public static Fy getInstance() {
                          Fy fy = new Fy1();
                          return fy;
                         
          //                Fy fy = new Fy1() {//這種匿名內部類是?蔡模?!
          //                        public void med1() {
          //                        }
          //                };               
          //                return fy;
                  }
          }

          //2
          interface Pdd {}

          class Pdd1 implements Pdd {}

          abstract class Fya {
                  public static Pdd getPd() {
                          Pdd pdd = new Pdd1();
                          return pdd;
                  }
          }

          //Prototype 在java中就是clone,又包o羈獎′和淺拷貝
          class CloneObja {
                  public CloneObja MyClone() {
                          return new CloneObja();
                  }
          }

          class CloneObjb {
                  public CloneObjb MyClone() throws Throwable {
                          CloneObjb cobj = null;
                          cobj = (CloneObjb) pcl(this);
                          return cobj;
                  }       
                 
                  //深度拷貝算法
                  private Object pcl(Object obj) throws Throwable {
                          ByteArrayOutputStream bao = new ByteArrayOutputStream(1000);
                          ObjectOutputStream objo = new ObjectOutputStream(bao);
                          objo.writeObject(obj);
                         
                          ByteArrayInputStream bai = new ByteArrayInputStream(bao.toByteArray());
                          ObjectInputStream obji = new ObjectInputStream(bai);
                         
                          Object objr = obji.readObject();
                          return objr;
                  }
          }

          //Singleton
          //一個類只有一個對象,例如一個線3壇?,一個cache
          class Singleton1 {
                  public static Singleton1 instance = new Singleton1();       
                 
                  private Singleton1() {               
                  }
                 
                  public static Singleton1 getInstance() {
                          return instance;
                  }
          }

          class Singleton2 {
                  public static Singleton2 instance;
                 
                  private Singleton2() {
                  }
                 
          //        public static Singleton2 getInstance() {               
          //                if (instance == null) {
          //                        instance = new Singleton2();
          //                }
          //               
          //                return instance;
          //        }
                 
                  public static Singleton2 getInstance() {
                          synchronized(Singleton2.class) {
                                  if (instance == null) {
                                          instance = new Singleton2();
                                  }
                          }
                         
                          return instance;
                  }
          }

          //**********結構型模式**********

          //Adapter
          //基本方法有兩種,一種是使用引用一種使用繼承
          //將不符合標準的接口轉成符合標準的接口,接口的修改主要是參數的?黽?,
          //返回值類型,當然還有方法名
          //感覺這就是封裝的另一種表示形式,封裝有用方法封裝(在方法中調用功能方法),
          //用類封裝(先傳入功能方法所在的類的對象,通過調用此對象的功能方法)

          //使用引用的形式
          class Adapteea {
                  public void kk() {}
          }

          interface Targeta {
                  String vv(int i, int k);
          }

          class Adaptera implements Targeta{
                  Adapteea ade;
                 
                  public Adaptera(Adapteea ade) {
                          this.ade = ade;
                  }
                 
                  public String vv(int i, int k) {
                          //具體的業務方法實現在Adaptee中,這個方法
                          //只起到了接口轉換的作用
                          //調用此方法是通過引用
                          ade.kk();
                          return null;
                  }
          }

          //使用繼承形式的
          class Adapteeb {
                  public void kk() {}
          }

          interface Targetb {
                  String vv(int i, int k);
          }

          class Adapterb extends Adapteeb implements Targetb {
                  public String vv(int i, int k) {
                          //調用此方法是通過繼承
                          kk();
                          return null;
                  }
          }

          //Proxy
          interface Subject {
                  void request();
          }

          class realSubject implements Subject {
                  public void request() {               
                          //do the real business
                  }
          }

          class Proxy implements Subject {
                  Subject subject;
                 
                  public Proxy(Subject subject) {
                          this.subject = subject;
                  }
                 
                  public void request() {
                          System.out.println("do something");
                         
                          subject.request();
                         
                          System.out.println("do something");
                  }
          }

          //Bridge
          //感覺就是多態的實現

          interface Imp {
                  void operation();
          }

          class Cimp1 implements Imp {
                  public void operation() {
                          System.out.println("1");
                  }
          }

          class Cimp2 implements Imp {
                  public void operation() {
                          System.out.println("2");
                  }
          }

          class Invoker {
                  Imp imp = new Cimp1();
                 
                  public void invoke() {
                          imp.operation();
                  }
          }

          //Composite

          interface Component {
                  void operation();
                 
                  void add(Component component);
                 
                  void remove(Component component);
          }

          class Leaf implements Component {
                  public void operation() {
                          System.out.println("an operation");
                  }
                 
                  public void add(Component component) {
                          throw new UnsupportedOperationException();
                  }
                 
                  public void remove(Component component) {
                          throw new UnsupportedOperationException();
                  }
          }

          class Composite implements Component {
                  List components = new ArrayList();
                 
                  public void operation() {
                          Component component = null;
                         
                          Iterator it = components.iterator();               
                          while (it.hasNext()) {
                                  //2恢來?component對象是leaf還是composite,
                                  //如果是leaf則直接實現操作,如果是composite則繼續遞歸調用
                                  component = (Component) it.next();
                                  component.operation();
                          }
                  }
                 
                  public void add(Component component) {               
                          components.add(component);
                  }
                 
                  public void remove(Component component) {               
                          components.remove(component);
                  }
          }

          //Decorator
          //對一個類的功能進行擴?故±,我可以使用繼承,但是2還?靈活,所以選用了
          //另外的一?中?式,引用與繼承都可活得對對象的一定的使用能力,而使用引用將更靈活
          //我?且a保證是對原功能的追加而不是修?模?則只能重寫方法,或使用新的方法
          //注意concrete的可以直接new出來,
          //而decorator的則需要用一個另外的decorator對象才能生成對象
          //使用對象封裝,和公用接口
          //Decorator鏈上可以有多個??

          interface Componenta {
                  void operation();
          }

          class ConcreteComponent implements Componenta {
                  public void operation() {
                          System.out.println("do something");
                  }
          }

          class Decorator implements Componenta {
                  private Componenta component;
                 
                  public Decorator(Componenta component) {
                          this.component = component;
                  }
                 
                  public void operation() {
                          //do something before
                         
                          component.operation();
                         
                          //do something after
                  }
          }

          //Facade
          //·淺Jμ用的一種設計模式,我可以為外部提供感興趣的接口

          class Obj1 {
                  public void ope1() {}
                  public void ope2() {}
          }

          class Obj2 {
                  public void ope1() {}
                  public void ope2() {}
          }

          class Facade {
                  //我μ玫攪?一個簡潔清晰的接口
                  public void fdMethod() {
                          Obj1 obj1 = new Obj1();
                          Obj2 obj2 = new Obj2();
                         
                          obj1.ope1();
                          obj2.ope2();
                  }
          }

          //Flyweight
          //空

          //**********行為型模式*************

          //Chain of Responsibility
          //與Decorator的實現形式相類似,
          //Decorator是在原來的方法之上進行添加功能,而
          //Chain則是?卸閑藕?如果不是當前處理的則轉?桓魷?一個?詰?處理
          //我可以使用if·種§來實現相同的效果,但是2還?靈活,鏈上的每個?詰?是可以替換?黽擁模?相對
          //比較靈活,我們可以設計接口實現對?詰?的增é靜ù作,而實現更方便的效果
          //這個是一個鏈狀的結構,有沒有?牘y使用環×唇á構

          interface Handler {
                  void handRequest(int signal);
          }

          class CHandler1 implements Handler {
                  private Handler handler;
                 
                  public CHandler1(Handler handler) {
                          this.handler = handler;
                  }
                 
                  public void handRequest(int signal) {
                          if (signal == 1) {
                                  System.out.println("handle signal 1");
                          }
                          else {
                                  handler.handRequest(signal);
                          }
                  }
          }

          class CHandler2 implements Handler {
                  private Handler handler;
                 
                  public CHandler2(Handler handler) {
                          this.handler = handler;
                  }
                 
                  public void handRequest(int signal) {
                          if (signal == 2) {
                                  System.out.println("handle signal 2");
                          }
                          else {
                                  handler.handRequest(signal);
                          }
                  }
          }

          class CHandler3 implements Handler {
                  public void handRequest(int signal) {
                          if (signal == 3) {
                                  System.out.println("handle signal 3");
                          }
                          else {
                                  throw new Error("can't handle signal");
                          }
                  }
          }

          class ChainClient {
                  public static void main(String[] args) {
                          Handler h3 = new CHandler3();
                          Handler h2 = new CHandler2(h3);
                          Handler h1 = new CHandler1(h2);
                         
                          h1.handRequest(2);
                  }
          }

          //Interpreter
          //感覺跟Composite很類似,只2還?分?鬧?結符和非終結符

          //Template Method

          abstract class TemplateMethod {
                  abstract void amd1();
                 
                  abstract void amd2();
                 
                  //此方法為一個Template Method方法
                  public void tmd() {
                          amd1();
                          amd2();
                  }
          }

          //State

          //標準型
          //狀ìí操作不應該耦合在一起
          class Contexta {
                  private State st;
                 
                  public Contexta(int nst) {
                          changeStfromNum(nst);
                  }
                 
                  public void changeStfromNum(int nst) {
                          if (nst == 1) {
                                  st = new CStatea1();
                          }
                          else if (nst == 2) {
                                  st = new CStatea2();
                          }
                         
                          throw new Error("bad state");
                  }
                 
                  void request() {
                          st.handle(this);
                  }
          }

          interface State {
                  void handle(Contexta context);
          }

          class CStatea1 implements State {
                  public void handle(Contexta context) {
                          System.out.println("state 1");
                          //也許在一個狀態的處理過程中要改變狀態,例如打開之后立即關閉這?中Ч?
                          //context.changeStfromNum(2);
                  }
          }

          class CStatea2 implements State {
                  public void handle(Contexta context) {
                          System.out.println("state 2");
                  }
          }

          //工廠型
          //根據狀態不通生成不同的state

          //class StateFactory {
          //        public static State getStateInstance(int num) {
          //                State st = null;
          //               
          //                if (num == 1) {
          //                        st = new CStatea1();
          //                }
          //                else if (num == 2) {
          //                        st = new CStatea2();
          //                }
          //               
          //                return st;
          //        }
          //}

          //Strategy
          //跟Bridge相類似,就是一種多態的表示

          //Visitor
          //雙向引用,使用另外的一個類調用自己的方法,訪問自己的數?萁á構
          interface Visitor {       
                  void visitElement(Elementd element);
          }

          class CVisitor implements Visitor {
                  public void visitElement(Elementd element) {
                          element.operation();
                  }
          }

          interface Elementd {       
                  void accept(Visitor visitor);
                 
                  void operation();
          }

          class CElementd implements Elementd {
                  public void accept(Visitor visitor) {
                          visitor.visitElement(this);
                  }
                 
                  public void operation() {
                          //實際的操作在這里
                  }
          }

          class Clientd {
                  public static void main() {
                          Elementd elm = new CElementd();
                          Visitor vis = new CVisitor();
                         
                          vis.visitElement(elm);
                  }
          }

          //Iteraotr
          //使用迭′÷對一個類的數?萁á構進D興承虻ú

          interface Structure {
                  interface Iteratora {
                          void first();
                         
                          boolean hasElement();
                         
                          Object next();
                         
                  }
          }

          class Structure1 implements Structure {
                  Object[] objs = new Object[100];
                 
                  //使用內部類是為了對Struture1的數?萁á構ó型耆?的訪問權
                  class Iteratora1 implements Iteratora {
                          int index = 0;
                         
                          public void first() {
                                  index = 0;
                          }
                         
                          public boolean hasElement() {
                                  return index < 100;
                          }
                         
                          public Object next() {
                                  Object obj = null;
                                 
                                  if (hasElement()) {
                                          obj = objs[index];
                                          index++;
                                  }
                                 
                                  return obj;
                          }
                  }
          }

          //Meditor

          class A1 {
                  public void operation1() {}
                  public void operation2() {}
          }

          class A2 {
                  public void operation1() {}
                  public void operation2() {}
          }

          class Mediator {
                  A1 a1;
                  A2 a2;
                 
                  public Mediator(A1 a1, A2 a2) {
                          this.a1 = a1;
                          this.a2 = a2;
                         
                  }
                 
                  //如果我想實現這個功能我可能會把他放在A1中
                  //但是這樣耦合大,我不想在A1中出現A2對象的引用,
                  //所以我使用了Mediator作為中介
                  public void mmed1() {
                          a1.operation1();
                          a2.operation2();
                  }
                 
                  public void mmed2() {
                          a2.operation1();
                          a1.operation2();
                  }
          }

          //Command
          //我認為就是將方法轉換成了類

          class Receiver {
                  public void action1() {}
                 
                  public void action2() {}
          }

          interface Command {
                  void Execute();
          }

          class CCommand1 implements Command {
                  private Receiver receiver;
                 
                  public CCommand1(Receiver receiver) {
                          this.receiver = receiver;
                  }
                 
                  public void Execute() {
                          receiver.action1();
                  }
          }

          class CCommand2 implements Command {
                  private Receiver receiver;
                 
                  public CCommand2(Receiver receiver) {
                          this.receiver = receiver;
                  }
                 
                  public void Execute() {
                          receiver.action2();
                  }
          }

          //Observer
          //在這里?此坪?這個模式沒有什么用
          //但是如果我有一個線程監控Subject,如果Subject的狀態
          //發生了變化,則更改Observer的狀態,并出發一些操作,這樣就有實際的ò庖?了
          //Observer與Visitor有相似的地方,都存在雙向引用
          //Subject可以注冊很多Observer

          interface Subjectb {
                  void attach(Observer observer);
                 
                  void detach(Observer observer);
                 
                  void mynotify();
                 
                  int getState();
                 
                  void setState(int state);
          }

          class Subjectb1 implements Subjectb {
                  List observers = new ArrayList();
                  int state;
                 
                  public void attach(Observer observer) {
                          observers.add(observer);
                  }
                 
                  public void detach(Observer observer) {
                          observers.remove(observer);
                  }
                 
                  public void mynotify() {
                          Observer observer = null;
                          Iterator it = observers.iterator();
                         
                          while (it.hasNext()) {
                                  observer = (Observer) it.next();
                                  observer.Update();
                          }
                  }

                  public int getState() {
                          return state;
                  }

                  public void setState(int state) {
                          this.state = state;
                  }
          }

          interface Observer {
                  void Update();
          }

          class Observer1 implements Observer {
                  Subjectb subject;
                  int state;
                 
                  public Observer1(Subjectb subject) {
                          this.subject = subject;
                  }
                 
                  public void Update() {               
                          this.state = subject.getState();
                  }
                 
                  public void operation() {
                          //一些基于state的操作
                  }
          }

          //Memento
          //感覺此模式沒有什?創笥?

          class Memento {
                  int state;

                  public int getState() {
                          return state;
                  }

                  public void setState(int state) {
                          this.state = state;
                  }
          }

          class Originator {
                  int state;
                 
                  public void setMemento(Memento memento) {
                          state = memento.getState();
                  }
                 
                  public Memento createMemento() {
                          Memento memento = new Memento();
                          memento.setState(1);
                          return memento;
                  }

                  public int getState() {
                          return state;
                  }

                  public void setState(int state) {
                          this.state = state;
                  }
          }

          class careTaker {
                  Memento memento;
                 
                  public void saverMemento(Memento memento) {
                          this.memento = memento;
                  }
                 
                  public Memento retrieveMemento() {
                          return memento;
                  }
          }

          //程序最終還是?承蛑′行μ模?是由不通部分的操作?唇ó起來的
          //將不同類的代碼?唇ó起來是通過引用實現μ模D了引用我就
          //相當ó謨D了一?ǚ?問數?萁á構和方法的能力,這與寫在類內部
          //差不多,例如我想將一個類中的一個方法抽離出去,因為這個方法依à滌?此類的數據和其他方法
          //直接將代碼移走是不行μ模?如果我們擁有了此類對象的引用,則與寫在此類
          //內部無異,所以我們擁有了引用就可以將此方法移出
          public class tt1 {
                  public static void main(String[] args) {
                  }
          }

           

          posted on 2009-03-15 22:10 大魚 閱讀(191) 評論(0)  編輯  收藏 所屬分類: j2se

          主站蜘蛛池模板: 平乡县| 宁德市| 唐河县| 汕头市| 磴口县| 定陶县| 石嘴山市| 杭州市| 钦州市| 尖扎县| 塔城市| 仪征市| 慈利县| 静宁县| 阿克苏市| 昌江| 蓬溪县| 浏阳市| 虹口区| 辛集市| 盐源县| 信宜市| 邹平县| 大城县| 民勤县| 兰西县| 沙田区| 青浦区| 康平县| 京山县| 游戏| 阜城县| 神农架林区| 句容市| 应城市| 耒阳市| 苍梧县| 嘉鱼县| 祁东县| 广丰县| 烟台市|