java设计模式演示样例
1.工廠方法模式(Factory Method) ?將程序中創(chuàng)建對象的操作,單獨(dú)出來處理,創(chuàng)建一個(gè)產(chǎn)品的工廠接口,把實(shí)際的工作轉(zhuǎn)移到詳細(xì)的子類。大大提高了系統(tǒng)擴(kuò)展的柔性,接口的抽象化處理給相互依賴的對象創(chuàng)建提供了最好的抽象模式。
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) 針對多個(gè)產(chǎn)品等級的情況,而工廠方法模式針對單一產(chǎn)品等級的情況。 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) 改善全局變量和命名空間的沖突,能夠說是一種改良了的全局變量。這樣的一個(gè)類僅僅有一個(gè)實(shí)例,且提供一個(gè)訪問全局點(diǎn)的方式,更加靈活的保證了實(shí)例的創(chuàng)建和訪問約束。系統(tǒng)中僅僅有一個(gè)實(shí)例,因此構(gòu)造方法應(yīng)該為私有 餓漢式:類載入時(shí)直接創(chuàng)建靜態(tài)實(shí)例 懶漢式:第一次須要時(shí)才創(chuàng)建一個(gè)實(shí)例,那么newInstance方法要加同步 餓漢式比懶漢式要好,雖然資源利用率要差。可是不用同步。 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) 將一個(gè)對象的內(nèi)部表象和建造過程切割,一個(gè)建造過程能夠造出不同表象的對象。可簡化為模版方法模式.
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) 通過一個(gè)原型對象來創(chuàng)建一個(gè)新對象(克隆)。Java中要給出Clonable接口的實(shí)現(xiàn),詳細(xì)類要實(shí)現(xiàn)這個(gè)接口,并給出clone()方法的實(shí)現(xiàn)細(xì)節(jié),這就是簡單原型模式的應(yīng)用。 ? 淺拷貝:僅僅拷貝簡單屬性的值和對象屬性的地址 ? 深拷貝:拷貝本對象引用的對象,有可能會出現(xiàn)循環(huán)引用的情況。能夠用串行化解決深拷貝。寫到流里再讀出來,這時(shí)會是一個(gè)對象的深拷貝結(jié)果。
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{}
結(jié)構(gòu)模式 怎樣把簡單的類依據(jù)某種結(jié)構(gòu)組裝為大的系統(tǒng)?
6.適配器模式(Adapter) 在原類型不做不論什么改變的情況下,用一個(gè)適配器類把一個(gè)接口轉(zhuǎn)成還有一個(gè)接口,擴(kuò)展了新的接口,靈活且多樣的適配一切舊俗。這樣的打破舊框框,適配新格局的思想,是面向?qū)ο蟮木琛R岳^承方式實(shí)現(xiàn)的類的 Adapter模式和以聚合方式實(shí)現(xiàn)的對象的Adapter模式,各有千秋,各取所長。
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的方法調(diào)用轉(zhuǎn)換成對useUSB的方法調(diào)用");usb.useUsb();}}?
7.組合模式(Composite) 把總體和局部的關(guān)系用樹狀結(jié)構(gòu)描寫敘述出來,使得client把總體對象和局部對象同等看待。
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) 以對客戶透明的方式來擴(kuò)展對象的功能。 用戶依據(jù)功能需求任意選取組成對象的成分,通過方法的鏈?zhǔn)秸{(diào)用來實(shí)現(xiàn)。 能夠給對象動(dòng)態(tài)的添加�功能,比繼承靈活性更大。
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) 用一個(gè)代理對象來作為還有一個(gè)對象的代理,對客戶來說是透明的。 存在一個(gè)抽象主題類,詳細(xì)主題類和代理主題類都繼承(實(shí)現(xiàn))抽象主題,代理主題類中的方法會調(diào)用詳細(xì)主題類中相相應(yīng)的方法。
10.享元模式(Flyweight Pattern) 對象的狀態(tài)分為內(nèi)蘊(yùn)狀態(tài)和外蘊(yùn)狀態(tài)。內(nèi)蘊(yùn)狀態(tài)不隨環(huán)境變化而變化,因此能夠作成系統(tǒng)共享.?
11.門面模式(Facade) 訪問子系統(tǒng)的時(shí)候,通過一個(gè)Fa?ade對象訪問。Facade類是單例的。 客戶代碼僅僅須要和門面對象通信,不須要和詳細(xì)子系統(tǒng)內(nèi)部的對象通信,使得他們之間的耦合關(guān)系減弱。 這次將表現(xiàn)層和邏輯層隔離,封裝底層的復(fù)雜處理,為用戶提供簡單的接口,這種樣例隨處可見。
門面模式非常多時(shí)候更是一種系統(tǒng)架構(gòu)的設(shè)計(jì),在我所做的項(xiàng)目中,就實(shí)現(xiàn)了門面模式的接口,為復(fù)雜系統(tǒng)的解耦提供了最好的解決方式。?
12.橋梁模式(Bridge) 將抽象和實(shí)現(xiàn)脫耦,使得二者能夠單獨(dú)變化。使得一個(gè)繼承關(guān)系不承擔(dān)兩個(gè)變化因素.使用合成來取代繼承的一種體現(xiàn).
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();}} ?
行為模式 描寫敘述怎樣在對象之間劃分責(zé)任?
13.策略模式(Strategy) 如同LayoutManager和詳細(xì)的布局管理器的關(guān)系,在抽象策略類中定義方法,將易于變化的部分封裝為接口,通常Strategy 封裝一些運(yùn)算法則,使之能互換。Bruce Zhang在他的博客中提到策略模式事實(shí)上是一種“面向接口”的編程方法,真是恰如其分。 在詳細(xì)策略子類中實(shí)現(xiàn),客戶代碼依據(jù)不同的須要選擇對應(yīng)的詳細(xì)類,比如電子商務(wù)中多種價(jià)格算法。 一種策略一旦選中,整個(gè)系統(tǒng)執(zhí)行期是不變化的
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) 準(zhǔn)備一個(gè)抽象類,把部分確定的邏輯定義在某些方法中,用其它抽象方法實(shí)現(xiàn)剩余的邏輯。不同子類對這些邏輯有不同的實(shí)現(xiàn)。 使用方法:定義多個(gè)抽象操作,定義并實(shí)現(xiàn)一個(gè)模板方法,將步驟放在這個(gè)詳細(xì)方法里,推遲到子類實(shí)現(xiàn)。子類能夠改變父類的可變部分,但不能改變模板方法所代表的頂級邏輯。 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("火車除夕,老同學(xué)見面");}public void gaoXiao(){System.out.println("名片當(dāng)作撲克");}public void shanQing(){System.out.println("馬家軍");}} ??
15.觀察者模式(Observer) 定義對象間的一種一對多的依賴關(guān)系,當(dāng)一個(gè)對象的狀態(tài)發(fā)生改變時(shí), 全部依賴于它的對象都得到通知并被自己主動(dòng)更新。觀察者和被觀察者的分開,為模塊劃分提供了清晰的界限。在低耦合的對象間完畢協(xié)調(diào)。 Java中的事件模型就是一個(gè)應(yīng)用。
16.迭代器模式(Iterator) 相似于集合中的Iterator,使用迭代器來統(tǒng)一不同集合對象的遍歷方式。在絕大多數(shù)的系統(tǒng)中,都會用到數(shù)組、集合、鏈表、隊(duì)列這種類型,關(guān)心迭代模式的來龍去脈很有必要。在遍歷算法中,迭代模式提供了遍歷的順序訪問容 器,GOF給出的定義為:提供一種方法訪問一個(gè)容器(container)對象中各個(gè)元素,而又不需暴露該對象的內(nèi)部細(xì)節(jié)。.NET中就是使用了迭代器來 創(chuàng)建用于foreach的集合。
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.責(zé)任鏈(Chain of Responsibility) 多個(gè)處理器對象連成一串,請求在這條鏈上傳遞,由該處理這個(gè)請求的處理器來處理。發(fā)出請求的client并不知道哪個(gè)對象處理請求。
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 "兩次password輸入不一致";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 "password長度必須為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.狀態(tài)模式(State) 在對象內(nèi)部狀態(tài)改變時(shí)改變其行為。把所研究的對象的行為封裝在不同的狀態(tài)對象中。
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("您處在游客狀態(tài),請先登錄");}}class NormalState extends State{public void action(){out.println("您處在正常狀態(tài),文章發(fā)表成功");}}class BlockedState extends State{public void action(){out.println("您處在被封狀態(tài),文章發(fā)表失敗");}}class NewComerState extends State{public void action(){out.println("您是新手,請先學(xué)習(xí)一下,3天后再來");}}class StateFactory{public static State createState(int i){if (i==1) return new GuestState();else return new NormalState();}}
19.備忘錄模式(Memento) 備忘錄對象用來存儲還有一個(gè)對象的快照對象,保存其內(nèi)部狀態(tài),使得能夠隨時(shí)恢復(fù)。 備忘錄角色:保存發(fā)起人對象的內(nèi)部狀態(tài),保護(hù)內(nèi)容不被除發(fā)起人對象之外的對象獲取。窄接口:負(fù)責(zé)人對象和其它對象看到的接口,僅僅同意把備忘錄對象傳給其它對象。寬接口:發(fā)起人能看到的接口,同意讀取內(nèi)部狀態(tài)。 發(fā)起人角色:創(chuàng)建并使用備忘錄對象來保存其狀態(tài) 負(fù)責(zé)人角色:負(fù)責(zé)保存?zhèn)渫泴ο蟆?? 白箱實(shí)現(xiàn):備忘錄類對其它類也可見,這樣發(fā)起人的狀態(tài)可能會存在安全問題。 ? 黑箱實(shí)現(xiàn):把備忘錄類作成發(fā)起人的內(nèi)部類,對外提供一個(gè)標(biāo)識接口。
public class TestMemento{public static void main(String[] args){Originator ori=new Originator();Caretaker c=new Caretaker();ori.setState("State 1");IFMemento m=ori.createMemento();c.save(m);ori.setState("State 2");m=c.retrieve();ori.restore(m);System.out.println("Now State:"+ori.getState());}}class Originator{String state;public void setState(String s){state=s;System.out.println("State change to: "+s);}public String getState(){return this.state;}public IFMemento createMemento(){return new Memento(state);}public void restore(IFMemento m){Memento mt=(Memento)m;this.state=mt.getState();}private class Memento implements IFMemento{private String state;public Memento(String s){this.state=s;}public String getState(){return this.state;}}}class Caretaker{private IFMemento m;public IFMemento retrieve(){return this.m;}public void save(IFMemento m){this.m=m;}}interface IFMemento{}
轉(zhuǎn)載于:https://www.cnblogs.com/yxwkf/p/3869818.html
總結(jié)
以上是生活随笔為你收集整理的java设计模式演示样例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《Windows Phone 8 Dev
- 下一篇: ListView添加项目带序列