我的java天地

          java常用模式代碼示例

          package designPattern;

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

          //*********創(chuàng)建型模式***************

          //factory method 1
          //1具體的構(gòu)造算法,和2構(gòu)造出的具體產(chǎn)品由子類實(shí)現(xiàn)
          interface Product {
          }

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

          abstract class Factory {
          abstract public Product fmd();

          //我認(rèn)為這個(gè)方方法的存在是,是對(duì)FactoryMethod方法的補(bǔ)充
          //例如可以為生成的對(duì)象賦值,計(jì)算為生成對(duì)象應(yīng)付何值,前后的日值
          //且這些都是公用的,生成產(chǎn)品的最主要算法還是在FactoryMethod中,
          //這個(gè)方法只是起輔助作用,這也是一種思維方法,將具體的算法實(shí)現(xiàn)在一個(gè)方法中
          //而我不直接調(diào)用此方法,而使用另外的一個(gè)方法封裝它,等到了更靈活的效果,而
          //子類需實(shí)現(xiàn)的內(nèi)容是FactoryMethod
          //此方法是一個(gè)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
          //這種方式簡(jiǎn)單實(shí)用
          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創(chuàng)建多個(gè)產(chǎn)品
          //感覺此模式?jīng)]有什么大用

          //當(dāng)然可以還有更多的接口
          interface Apda {}

          interface Apdb {}

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

          class Apda1 implements Apda {}

          class Apdb1 implements Apdb {}

          //有幾個(gè)接口就有幾個(gè)對(duì)應(yīng)的方法
          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
          //一個(gè)產(chǎn)品的生成分為生成部件和組裝部件,不同的產(chǎn)品每個(gè)部件生成的方式不同
          //而組裝的方式相同,部件的生成抽象成接口方法,而組裝的方法使用一個(gè)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();

          //對(duì)對(duì)象的內(nèi)容進(jìn)行設(shè)置
          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();
          }
          }

          //一個(gè)簡(jiǎn)單的生成產(chǎn)品的實(shí)現(xiàn)
          //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() {//這種匿名內(nèi)部類是靜態(tài)的!!
          //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,又包含深拷貝和淺拷貝
          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
          //一個(gè)類只有一個(gè)對(duì)象,例如一個(gè)線程池,一個(gè)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;
          }
          }

          ?

          //**********結(jié)構(gòu)型模式**********

          //Adapter
          //基本方法有兩種,一種是使用引用一種使用繼承
          //將不符合標(biāo)準(zhǔn)的接口轉(zhuǎn)成符合標(biāo)準(zhǔn)的接口,接口的修改主要是參數(shù)的增減,
          //返回值類型,當(dāng)然還有方法名
          //感覺這就是封裝的另一種表示形式,封裝有用方法封裝(在方法中調(diào)用功能方法),
          //用類封裝(先傳入功能方法所在的類的對(duì)象,通過調(diào)用此對(duì)象的功能方法)

          //使用引用的形式
          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) {
          //具體的業(yè)務(wù)方法實(shí)現(xiàn)在Adaptee中,這個(gè)方法
          //只起到了接口轉(zhuǎn)換的作用
          //調(diào)用此方法是通過引用
          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) {
          //調(diào)用此方法是通過繼承
          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
          //感覺就是多態(tài)的實(shí)現(xiàn)

          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()) {
          //不知道此component對(duì)象是leaf還是composite,
          //如果是leaf則直接實(shí)現(xiàn)操作,如果是composite則繼續(xù)遞歸調(diào)用
          component = (Component) it.next();
          component.operation();
          }
          }

          public void add(Component component) {
          components.add(component);
          }

          public void remove(Component component) {
          components.remove(component);
          }
          }

          //Decorator
          //對(duì)一個(gè)類的功能進(jìn)行擴(kuò)展時(shí),我可以使用繼承,但是不夠靈活,所以選用了
          //另外的一種形式,引用與繼承都可活得對(duì)對(duì)象的一定的使用能力,而使用引用將更靈活
          //我們要保證是對(duì)原功能的追加而不是修改,否則只能重寫方法,或使用新的方法
          //注意concrete的可以直接new出來,
          //而decorator的則需要用一個(gè)另外的decorator對(duì)象才能生成對(duì)象
          //使用對(duì)象封裝,和公用接口
          //Decorator鏈上可以有多個(gè)元素

          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
          //非常實(shí)用的一種設(shè)計(jì)模式,我可以為外部提供感興趣的接口

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

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

          class Facade {
          //我得到了一個(gè)簡(jiǎn)潔清晰的接口
          public void fdMethod() {
          Obj1 obj1 = new Obj1();
          Obj2 obj2 = new Obj2();

          obj1.ope1();
          obj2.ope2();
          ?}
          }

          //Flyweight
          //空


          ?

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

          //Chain of Responsibility
          //與Decorator的實(shí)現(xiàn)形式相類似,
          //Decorator是在原來的方法之上進(jìn)行添加功能,而
          //Chain則是判斷信號(hào)如果不是當(dāng)前處理的則轉(zhuǎn)交個(gè)下一個(gè)節(jié)點(diǎn)處理
          //我可以使用if分支來實(shí)現(xiàn)相同的效果,但是不夠靈活,鏈上的每個(gè)節(jié)點(diǎn)是可以替換增加的,相對(duì)
          //比較靈活,我們可以設(shè)計(jì)接口實(shí)現(xiàn)對(duì)節(jié)點(diǎn)的增刪操作,而實(shí)現(xiàn)更方便的效果
          //這個(gè)是一個(gè)鏈狀的結(jié)構(gòu),有沒有想過使用環(huán)狀結(jié)構(gòu)

          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很類似,只不過他分文終結(jié)符和非終結(jié)符

          //Template Method

          abstract class TemplateMethod {
          abstract void amd1();

          abstract void amd2();

          //此方法為一個(gè)Template Method方法
          public void tmd() {
          amd1();
          amd2();
          }
          }

          //State

          //標(biāo)準(zhǔn)型
          //狀態(tài)和操作不應(yīng)該耦合在一起
          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");
          //也許在一個(gè)狀態(tài)的處理過程中要改變狀態(tài),例如打開之后立即關(guān)閉這種效果
          //context.changeStfromNum(2);
          }
          }

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

          //工廠型
          //根據(jù)狀態(tài)不通生成不同的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相類似,就是一種多態(tài)的表示

          //Visitor
          //雙向引用,使用另外的一個(gè)類調(diào)用自己的方法,訪問自己的數(shù)據(jù)結(jié)構(gòu)
          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() {
          //實(shí)際的操作在這里
          }
          }

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

          vis.visitElement(elm);
          }
          }

          //Iteraotr
          //使用迭代器對(duì)一個(gè)類的數(shù)據(jù)結(jié)構(gòu)進(jìn)行順序迭代

          interface Structure {
          interface Iteratora {
          void first();

          boolean hasElement();

          Object next();

          }
          }

          class Structure1 implements Structure {
          Object[] objs = new Object[100];

          //使用內(nèi)部類是為了對(duì)Struture1的數(shù)據(jù)結(jié)構(gòu)有完全的訪問權(quán)
          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;

          }

          //如果我想實(shí)現(xiàn)這個(gè)功能我可能會(huì)把他放在A1中
          //但是這樣耦合大,我不想在A1中出現(xiàn)A2對(duì)象的引用,
          //所以我使用了Mediator作為中介
          public void mmed1() {
          a1.operation1();
          a2.operation2();
          }

          public void mmed2() {
          a2.operation1();
          a1.operation2();
          }
          }

          //Command
          //我認(rèn)為就是將方法轉(zhuǎn)換成了類

          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
          //在這里看似乎這個(gè)模式?jīng)]有什么用
          //但是如果我有一個(gè)線程監(jiān)控Subject,如果Subject的狀態(tài)
          //發(fā)生了變化,則更改Observer的狀態(tài),并出發(fā)一些操作,這樣就有實(shí)際的意義了
          //Observer與Visitor有相似的地方,都存在雙向引用
          //Subject可以注冊(cè)很多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
          //感覺此模式?jīng)]有什么大用

          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;
          }
          }

          //程序最終還是順序執(zhí)行的,是由不通部分的操作拼接起來的
          //將不同類的代碼拼接起來是通過引用實(shí)現(xiàn)的,有了引用我就
          //相當(dāng)于有了一定訪問數(shù)據(jù)結(jié)構(gòu)和方法的能力,這與寫在類內(nèi)部
          //差不多,例如我想將一個(gè)類中的一個(gè)方法抽離出去,因?yàn)檫@個(gè)方法依賴與此類的數(shù)據(jù)和其他方法
          //直接將代碼移走是不行的,但如果我們擁有了此類對(duì)象的引用,則與寫在此類
          //內(nèi)部無異,所以我們擁有了引用就可以將此方法移出
          public class Pattern {
          public static void main(String[] args) {
          }
          }

          ?

          posted on 2010-08-18 11:31 tobyxiong 閱讀(416) 評(píng)論(0)  編輯  收藏 所屬分類: design

          <2010年8月>
          25262728293031
          1234567
          891011121314
          15161718192021
          22232425262728
          2930311234

          導(dǎo)航

          統(tǒng)計(jì)

          常用鏈接

          留言簿(3)

          隨筆分類(144)

          隨筆檔案(157)

          相冊(cè)

          最新隨筆

          搜索

          積分與排名

          最新評(píng)論

          閱讀排行榜

          評(píng)論排行榜

          主站蜘蛛池模板: 伽师县| 柳林县| 乐平市| 平塘县| 保康县| 凌云县| 阿拉善盟| 全州县| 夏河县| 仲巴县| 贞丰县| 唐河县| 图片| 丹寨县| 钟祥市| 大港区| 东安县| 靖宇县| 虞城县| 波密县| 依兰县| 竹山县| 昭觉县| 三江| 松江区| 江门市| 阳朔县| 乌审旗| 江山市| 龙门县| 淅川县| 胶南市| 宜丰县| 乡城县| 汝南县| 安徽省| 阳原县| 塔城市| 名山县| 焦作市| 大名县|