23種設計模式的代碼版

來源:互聯網
上載者:User
最討厭廢話了,把代碼貼出來最簡單。

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中,
//這個方法只是起輔助作用,這也是一種思維方法,將具體的演算法實現在一個方法中
//而我不直接調用此方法,而使用另外的一個方法封裝它,等到了更靈活的效果,而
//子類需實現的內容是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,又包含深拷貝和淺拷貝
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
//一個類只有一個對象,例如一個線程池,一個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()) {
//不知道此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
//對一個類的功能進行擴充時,我可以使用繼承,但是不夠靈活,所以選用了
//另外的一種形式,引用與繼承都可活得對對象的一定的使用能力,而使用引用將更靈活
//我們要保證是對原功能的追加而不是修改,否則只能重寫方法,或使用新的方法
//注意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
//非常實用的一種設計模式,我可以為外部提供感興趣的介面

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分支來實現相同的效果,但是不夠靈活,鏈上的每個節點是可以替換增加的,相對
//比較靈活,我們可以設計介面實現對節點的增刪操作,而實現更方便的效果
//這個是一個鏈狀的結構,有沒有想過使用環狀結構

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

//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
//使用迭代器對一個類的資料結構進行順序迭代

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

//程式最終還是順序執行的,是由不通部分的操作拼接起來的
//將不同類的代碼拼接起來是通過引用實現的,有了引用我就
//相當於有了一定訪問資料結構和方法的能力,這與寫在類內部
//差不多,例如我想將一個類中的一個方法抽離出去,因為這個方法依賴與此類的資料和其他方法
//直接將代碼移走是不行的,但如果我們擁有了此類對象的引用,則與寫在此類
//內部無異,所以我們擁有了引用就可以將此方法移出
public class tt1 {
public static void main(String[] args) {
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.