設(shè)計(jì)模式也可以這么簡(jiǎn)單

作者:hongjie 來(lái)源:https://javadoop.com/post/design-pattern
面向接口編程,而不是面向?qū)崿F(xiàn)。這個(gè)很重要,也是優(yōu)雅的、可擴(kuò)展的代碼的第一步,這就不需要多說(shuō)了吧。
職責(zé)單一原則。每個(gè)類都應(yīng)該只有一個(gè)單一的功能,并且該功能應(yīng)該由這個(gè)類完全封裝起來(lái)。
對(duì)修改關(guān)閉,對(duì)擴(kuò)展開(kāi)放。對(duì)修改關(guān)閉是說(shuō),我們辛辛苦苦加班寫出來(lái)的代碼,該實(shí)現(xiàn)的功能和該修復(fù)的 bug 都完成了,別人可不能說(shuō)改就改;對(duì)擴(kuò)展開(kāi)放就比較好理解了,也就是說(shuō)在我們寫好的代碼基礎(chǔ)上,很容易實(shí)現(xiàn)擴(kuò)展。
創(chuàng)建型模式
簡(jiǎn)單工廠模式
public classFoodFactory{
publicstatic Food makeFood(String name) {
if (name.equals("noodle")) {
Food noodle = new LanZhouNoodle();
noodle.addSpicy("more");
return noodle;
} else if (name.equals("chicken")) {
Food chicken = new HuangMenChicken();
chicken.addCondiment("potato");
return chicken;
} else {
return null;
}
}
}
我們強(qiáng)調(diào)職責(zé)單一原則,一個(gè)類只提供一種功能,F(xiàn)oodFactory 的功能就是只要負(fù)責(zé)生產(chǎn)各種 Food。
工廠模式
public interfaceFoodFactory{
Food makeFood(String name);
}
public classChineseFoodFactoryimplementsFoodFactory{
@Override
public Food makeFood(String name) {
if (name.equals("A")) {
return new ChineseFoodA();
} else if (name.equals("B")) {
return new ChineseFoodB();
} else {
return null;
}
}
}
public classAmericanFoodFactoryimplementsFoodFactory{
@Override
public Food makeFood(String name) {
if (name.equals("A")) {
return new AmericanFoodA();
} else if (name.equals("B")) {
return new AmericanFoodB();
} else {
return null;
}
}
}
public classAPP{
publicstaticvoidmain(String[] args) {
// 先選擇一個(gè)具體的工廠
FoodFactory factory = new ChineseFoodFactory();
// 由第一步的工廠產(chǎn)生具體的對(duì)象,不同的工廠造出不一樣的對(duì)象
Food food = factory.makeFood("A");
}
}

抽象工廠模式

// 得到 Intel 的 CPU
CPUFactory cpuFactory = new IntelCPUFactory();
CPU cpu = intelCPUFactory.makeCPU();
// 得到 AMD 的主板
MainBoardFactory mainBoardFactory = new AmdMainBoardFactory();
MainBoard mainBoard = mainBoardFactory.make();
// 組裝 CPU 和主板
Computer computer = new Computer(cpu, mainBoard);


publicstaticvoidmain(String[] args) {
// 第一步就要選定一個(gè)“大廠”
ComputerFactory cf = new AmdFactory();
// 從這個(gè)大廠造 CPU
CPU cpu = cf.makeCPU();
// 從這個(gè)大廠造主板
MainBoard board = cf.makeMainBoard();
// 從這個(gè)大廠造硬盤
HardDisk hardDisk = cf.makeHardDisk();
// 將同一個(gè)廠子出來(lái)的 CPU、主板、硬盤組裝在一起
Computer result = new Computer(cpu, board, hardDisk);
}
單例模式
public classSingleton{
// 首先,將 new Singleton() 堵死
privateSingleton() {};
// 創(chuàng)建私有靜態(tài)實(shí)例,意味著這個(gè)類第一次使用的時(shí)候就會(huì)進(jìn)行創(chuàng)建
private static Singleton instance = new Singleton();
publicstatic Singleton getInstance() {
return instance;
}
// 瞎寫一個(gè)靜態(tài)方法。這里想說(shuō)的是,如果我們只是要調(diào)用 Singleton.getDate(...),
// 本來(lái)是不想要生成 Singleton 實(shí)例的,不過(guò)沒(méi)辦法,已經(jīng)生成了
publicstatic Date getDate(String mode) {return new Date();}
}
很多人都能說(shuō)出餓漢模式的缺點(diǎn),可是我覺(jué)得生產(chǎn)過(guò)程中,很少碰到這種情況:你定義了一個(gè)單例的類,不需要其實(shí)例,可是你卻把一個(gè)或幾個(gè)你會(huì)用到的靜態(tài)方法塞到這個(gè)類中。
public classSingleton{
// 首先,也是先堵死 new Singleton() 這條路
privateSingleton() {}
// 和餓漢模式相比,這邊不需要先實(shí)例化出來(lái),注意這里的 volatile,它是必須的
private static volatile Singleton instance = null;
publicstatic Singleton getInstance() {
if (instance == null) {
// 加鎖
synchronized (Singleton.class) {
// 這一次判斷也是必須的,不然會(huì)有并發(fā)問(wèn)題
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
雙重檢查,指的是兩次檢查 instance 是否為 null。 volatile 在這里是需要的,希望能引起讀者的關(guān)注。 很多人不知道怎么寫,直接就在 getInstance() 方法簽名上加上 synchronized,這就不多說(shuō)了,性能太差。
public classSingleton3{
privateSingleton3() {}
// 主要是使用了 嵌套類可以訪問(wèn)外部類的靜態(tài)屬性和靜態(tài)方法 的特性
private static classHolder{
private static Singleton3 instance = new Singleton3();
}
publicstatic Singleton3 getInstance() {
return Holder.instance;
}
}
注意,很多人都會(huì)把這個(gè)嵌套類說(shuō)成是靜態(tài)內(nèi)部類,嚴(yán)格地說(shuō),內(nèi)部類和嵌套類是不一樣的,它們能訪問(wèn)的外部類權(quán)限也是不一樣的。
建造者模式
Food food = new FoodBuilder().a().b().c().build();
Food food = Food.builder().a().b().c().build();
classUser{
// 下面是“一堆”的屬性
private String name;
private String password;
private String nickName;
private int age;
// 構(gòu)造方法私有化,不然客戶端就會(huì)直接調(diào)用構(gòu)造方法了
privateUser(String name, String password, String nickName, int age) {
this.name = name;
this.password = password;
this.nickName = nickName;
this.age = age;
}
// 靜態(tài)方法,用于生成一個(gè) Builder,這個(gè)不一定要有,不過(guò)寫這個(gè)方法是一個(gè)很好的習(xí)慣,
// 有些代碼要求別人寫 new User.UserBuilder().a()...build() 看上去就沒(méi)那么好
publicstatic UserBuilder builder() {
return new UserBuilder();
}
public static classUserBuilder{
// 下面是和 User 一模一樣的一堆屬性
private String name;
private String password;
private String nickName;
private int age;
privateUserBuilder() {
}
// 鏈?zhǔn)秸{(diào)用設(shè)置各個(gè)屬性值,返回 this,即 UserBuilder
public UserBuilder name(String name) {
this.name = name;
return this;
}
public UserBuilder password(String password) {
this.password = password;
return this;
}
public UserBuilder nickName(String nickName) {
this.nickName = nickName;
return this;
}
public UserBuilder age(int age) {
this.age = age;
return this;
}
// build() 方法負(fù)責(zé)將 UserBuilder 中設(shè)置好的屬性“復(fù)制”到 User 中。
// 當(dāng)然,可以在 “復(fù)制” 之前做點(diǎn)檢驗(yàn)
public User build() {
if (name == null || password == null) {
throw new RuntimeException("用戶名和密碼必填");
}
if (age <= 0 || age >= 150) {
throw new RuntimeException("年齡不合法");
}
// 還可以做賦予”默認(rèn)值“的功能
if (nickName == null) {
nickName = name;
}
return new User(name, password, nickName, age);
}
}
}
public classAPP{
publicstaticvoidmain(String[] args) {
User d = User.builder()
.name("foo")
.password("pAss12345")
.age(25)
.build();
}
}
題外話,強(qiáng)烈建議讀者使用 lombok,用了 lombok 以后,上面的一大堆代碼會(huì)變成如下這樣:
@Builder
classUser{
private String name;
private String password;
private String nickName;
private int age;
}
怎么樣,省下來(lái)的時(shí)間是不是又可以干點(diǎn)別的了。
User user = new User().setName("").setPassword("").setAge(20);
很多人是這么用的,但是筆者覺(jué)得其實(shí)這種寫法非常地不優(yōu)雅,不是很推薦使用。
原型模式
protectednative Object clone() throws CloneNotSupportedException;
java 的克隆是淺克隆,碰到對(duì)象引用的時(shí)候,克隆出來(lái)的對(duì)象和原對(duì)象中的引用將指向同一個(gè)對(duì)象。通常實(shí)現(xiàn)深克隆的方法是將對(duì)象進(jìn)行序列化,然后再進(jìn)行反序列化。
創(chuàng)建型模式總結(jié)
結(jié)構(gòu)型模式
代理模式
理解代理這個(gè)詞,這個(gè)模式其實(shí)就簡(jiǎn)單了。
public interfaceFoodService{
Food makeChicken();
Food makeNoodle();
}
public classFoodServiceImplimplementsFoodService{
public Food makeChicken() {
Food f = new Chicken()
f.setChicken("1kg");
f.setSpicy("1g");
f.setSalt("3g");
return f;
}
public Food makeNoodle() {
Food f = new Noodle();
f.setNoodle("500g");
f.setSalt("5g");
return f;
}
}
// 代理要表現(xiàn)得“就像是”真實(shí)實(shí)現(xiàn)類,所以需要實(shí)現(xiàn) FoodService
public classFoodServiceProxyimplementsFoodService{
// 內(nèi)部一定要有一個(gè)真實(shí)的實(shí)現(xiàn)類,當(dāng)然也可以通過(guò)構(gòu)造方法注入
private FoodService foodService = new FoodServiceImpl();
public Food makeChicken() {
System.out.println("我們馬上要開(kāi)始制作雞肉了");
// 如果我們定義這句為核心代碼的話,那么,核心代碼是真實(shí)實(shí)現(xiàn)類做的,
// 代理只是在核心代碼前后做些“無(wú)足輕重”的事情
Food food = foodService.makeChicken();
System.out.println("雞肉制作完成啦,加點(diǎn)胡椒粉"); // 增強(qiáng)
food.addCondiment("pepper");
return food;
}
public Food makeNoodle() {
System.out.println("準(zhǔn)備制作拉面~");
Food food = foodService.makeNoodle();
System.out.println("制作完成啦")
return food;
}
}
// 這里用代理類來(lái)實(shí)例化
FoodService foodService = new FoodServiceProxy();
foodService.makeChicken();

適配器模式
默認(rèn)適配器模式
public interfaceFileAlterationListener{
voidonStart(final FileAlterationObserver observer);
voidonDirectoryCreate(final File directory);
voidonDirectoryChange(final File directory);
voidonDirectoryDelete(final File directory);
voidonFileCreate(final File file);
voidonFileChange(final File file);
voidonFileDelete(final File file);
voidonStop(final FileAlterationObserver observer);
}
public classFileAlterationListenerAdaptorimplementsFileAlterationListener{
publicvoidonStart(final FileAlterationObserver observer) {
}
publicvoidonDirectoryCreate(final File directory) {
}
publicvoidonDirectoryChange(final File directory) {
}
publicvoidonDirectoryDelete(final File directory) {
}
publicvoidonFileCreate(final File file) {
}
publicvoidonFileChange(final File file) {
}
publicvoidonFileDelete(final File file) {
}
publicvoidonStop(final FileAlterationObserver observer) {
}
}
public classFileMonitorextendsFileAlterationListenerAdaptor{
publicvoidonFileCreate(final File file) {
// 文件創(chuàng)建
doSomething();
}
publicvoidonFileDelete(final File file) {
// 文件刪除
doSomething();
}
}
對(duì)象適配器模式
public interfaceDuck{
publicvoidquack(); // 鴨的呱呱叫
publicvoidfly(); // 飛
}
public interfaceCock{
publicvoidgobble(); // 雞的咕咕叫
publicvoidfly(); // 飛
}
public classWildCockimplementsCock{
publicvoidgobble() {
System.out.println("咕咕叫");
}
publicvoidfly() {
System.out.println("雞也會(huì)飛哦");
}
}
// 毫無(wú)疑問(wèn),首先,這個(gè)適配器肯定需要 implements Duck,這樣才能當(dāng)做鴨來(lái)用
public classCockAdapterimplementsDuck{
Cock cock;
// 構(gòu)造方法中需要一個(gè)雞的實(shí)例,此類就是將這只雞適配成鴨來(lái)用
publicCockAdapter(Cock cock) {
this.cock = cock;
}
// 實(shí)現(xiàn)鴨的呱呱叫方法
@Override
publicvoidquack() {
// 內(nèi)部其實(shí)是一只雞的咕咕叫
cock.gobble();
}
@Override
publicvoidfly() {
cock.fly();
}
}
publicstaticvoidmain(String[] args) {
// 有一只野雞
Cock wildCock = new WildCock();
// 成功將野雞適配成鴨
Duck duck = new CockAdapter(wildCock);
...
}

類適配器模式

Target t = new SomeAdapter(); 就可以了。適配器模式總結(jié)
類適配和對(duì)象適配的異同
一個(gè)采用繼承,一個(gè)采用組合;
類適配屬于靜態(tài)實(shí)現(xiàn),對(duì)象適配屬于組合的動(dòng)態(tài)實(shí)現(xiàn),對(duì)象適配需要多實(shí)例化一個(gè)對(duì)象。
總體來(lái)說(shuō),對(duì)象適配用得比較多。
適配器模式和代理模式的異同
比較這兩種模式,其實(shí)是比較對(duì)象適配器模式和代理模式,在代碼結(jié)構(gòu)上,它們很相似,都需要一個(gè)具體的實(shí)現(xiàn)類的實(shí)例。但是它們的目的不一樣,代理模式做的是增強(qiáng)原方法的活;適配器做的是適配的活,為的是提供“把雞包裝成鴨,然后當(dāng)做鴨來(lái)使用”,而雞和鴨它們之間原本沒(méi)有繼承關(guān)系。

橋梁模式
public interfaceDrawAPI{
publicvoiddraw(int radius, int x, int y);
}
public classRedPenimplementsDrawAPI{
@Override
publicvoiddraw(int radius, int x, int y) {
System.out.println("用紅色筆畫圖,radius:" + radius + ", x:" + x + ", y:" + y);
}
}
public classGreenPenimplementsDrawAPI{
@Override
publicvoiddraw(int radius, int x, int y) {
System.out.println("用綠色筆畫圖,radius:" + radius + ", x:" + x + ", y:" + y);
}
}
public classBluePenimplementsDrawAPI{
@Override
publicvoiddraw(int radius, int x, int y) {
System.out.println("用藍(lán)色筆畫圖,radius:" + radius + ", x:" + x + ", y:" + y);
}
}
public abstract classShape{
protected DrawAPI drawAPI;
protectedShape(DrawAPI drawAPI) {
this.drawAPI = drawAPI;
}
publicabstractvoiddraw();
}
// 圓形
public classCircleextendsShape{
private int radius;
publicCircle(int radius, DrawAPI drawAPI) {
super(drawAPI);
this.radius = radius;
}
publicvoiddraw() {
drawAPI.draw(radius, 0, 0);
}
}
// 長(zhǎng)方形
public classRectangleextendsShape{
private int x;
private int y;
publicRectangle(int x, int y, DrawAPI drawAPI) {
super(drawAPI);
this.x = x;
this.y = y;
}
publicvoiddraw() {
drawAPI.draw(0, x, y);
}
}
publicstaticvoidmain(String[] args) {
Shape greenCircle = new Circle(10, new GreenPen());
Shape redRectangle = new Rectangle(4, 8, new RedPen());
greenCircle.draw();
redRectangle.draw();
}

本節(jié)引用了這里的例子,并對(duì)其進(jìn)行了修改。
裝飾模式

Component 其實(shí)已經(jīng)有了 ConcreteComponentA 和 ConcreteComponentB 兩個(gè)實(shí)現(xiàn)類了,但是,如果我們要增強(qiáng)這兩個(gè)實(shí)現(xiàn)類的話,我們就可以采用裝飾模式,用具體的裝飾器來(lái)裝飾實(shí)現(xiàn)類,以達(dá)到增強(qiáng)的目的。從名字來(lái)簡(jiǎn)單解釋下裝飾器。既然說(shuō)是裝飾,那么往往就是添加小功能這種,而且,我們要滿足可以添加多個(gè)小功能。最簡(jiǎn)單的,代理模式就可以實(shí)現(xiàn)功能的增強(qiáng),但是代理不容易實(shí)現(xiàn)多個(gè)功能的增強(qiáng),當(dāng)然你可以說(shuō)用代理包裝代理的多層包裝方式,但是那樣的話代碼就復(fù)雜了。
注意這段話中混雜在各個(gè)名詞中的 Component 和 Decorator,別搞混了。
public abstract classBeverage{
// 返回描述
publicabstract String getDescription();
// 返回價(jià)格
publicabstractdoublecost();
}
public classBlackTeaextendsBeverage{
public String getDescription() {
return "紅茶";
}
publicdoublecost() {
return 10;
}
}
public classGreenTeaextendsBeverage{
public String getDescription() {
return "綠茶";
}
publicdoublecost() {
return 11;
}
}
...// 咖啡省略
// 調(diào)料
public abstract classCondimentextendsBeverage{
}
public classLemonextendsCondiment{
private Beverage bevarage;
// 這里很關(guān)鍵,需要傳入具體的飲料,如需要傳入沒(méi)有被裝飾的紅茶或綠茶,
// 當(dāng)然也可以傳入已經(jīng)裝飾好的芒果綠茶,這樣可以做芒果檸檬綠茶
publicLemon(Beverage bevarage) {
this.bevarage = bevarage;
}
public String getDescription() {
// 裝飾
return bevarage.getDescription() + ", 加檸檬";
}
publicdoublecost() {
// 裝飾
return beverage.cost() + 2; // 加檸檬需要 2 元
}
}
public classMangoextendsCondiment{
private Beverage bevarage;
publicMango(Beverage bevarage) {
this.bevarage = bevarage;
}
public String getDescription() {
return bevarage.getDescription() + ", 加芒果";
}
publicdoublecost() {
return beverage.cost() + 3; // 加芒果需要 3 元
}
}
...// 給每一種調(diào)料都加一個(gè)類
publicstaticvoidmain(String[] args) {
// 首先,我們需要一個(gè)基礎(chǔ)飲料,紅茶、綠茶或咖啡
Beverage beverage = new GreenTea();
// 開(kāi)始裝飾
beverage = new Lemon(beverage); // 先加一份檸檬
beverage = new Mongo(beverage); // 再加一份芒果
System.out.println(beverage.getDescription() + " 價(jià)格:¥" + beverage.cost());
//"綠茶, 加檸檬, 加芒果 價(jià)格:¥16"
}
Beverage beverage = new Mongo(new Pearl(new Lemon(new Lemon(new BlackTea()))));


InputStream inputStream = new LineNumberInputStream(new BufferedInputStream(new FileInputStream("")));
DataInputStream is = new DataInputStream(
new BufferedInputStream(
new FileInputStream("")));
所以說(shuō)嘛,要找到純的嚴(yán)格符合設(shè)計(jì)模式的代碼還是比較難的。
門面模式
public interfaceShape{
voiddraw();
}
public classCircleimplementsShape{
@Override
publicvoiddraw() {
System.out.println("Circle::draw()");
}
}
public classRectangleimplementsShape{
@Override
publicvoiddraw() {
System.out.println("Rectangle::draw()");
}
}
publicstaticvoidmain(String[] args) {
// 畫一個(gè)圓形
Shape circle = new Circle();
circle.draw();
// 畫一個(gè)長(zhǎng)方形
Shape rectangle = new Rectangle();
rectangle.draw();
}
public classShapeMaker{
private Shape circle;
private Shape rectangle;
private Shape square;
publicShapeMaker() {
circle = new Circle();
rectangle = new Rectangle();
square = new Square();
}
/**
* 下面定義一堆方法,具體應(yīng)該調(diào)用什么方法,由這個(gè)門面來(lái)決定
*/
publicvoiddrawCircle(){
circle.draw();
}
publicvoiddrawRectangle(){
rectangle.draw();
}
publicvoiddrawSquare(){
square.draw();
}
}
publicstaticvoidmain(String[] args) {
ShapeMaker shapeMaker = new ShapeMaker();
// 客戶端調(diào)用現(xiàn)在更加清晰了
shapeMaker.drawCircle();
shapeMaker.drawRectangle();
shapeMaker.drawSquare();
}
組合模式
public classEmployee{
private String name;
private String dept;
private int salary;
private Listsubordinates; // 下屬
publicEmployee(String name,String dept, int sal) {
this.name = name;
this.dept = dept;
this.salary = sal;
subordinates = new ArrayList();
}
publicvoidadd(Employee e) {
subordinates.add(e);
}
publicvoidremove(Employee e) {
subordinates.remove(e);
}
public ListgetSubordinates() {
return subordinates;
}
public String toString(){
return ("Employee :[ Name : " + name + ", dept : " + dept + ", salary :" + salary+" ]");
}
}
享元模式
結(jié)構(gòu)型模式總結(jié)
?行為型模式
策略模式
public interfaceStrategy{
publicvoiddraw(int radius, int x, int y);
}
public classRedPenimplementsStrategy{
@Override
publicvoiddraw(int radius, int x, int y) {
System.out.println("用紅色筆畫圖,radius:" + radius + ", x:" + x + ", y:" + y);
}
}
public classGreenPenimplementsStrategy{
@Override
publicvoiddraw(int radius, int x, int y) {
System.out.println("用綠色筆畫圖,radius:" + radius + ", x:" + x + ", y:" + y);
}
}
public classBluePenimplementsStrategy{
@Override
publicvoiddraw(int radius, int x, int y) {
System.out.println("用藍(lán)色筆畫圖,radius:" + radius + ", x:" + x + ", y:" + y);
}
}
public classContext{
private Strategy strategy;
publicContext(Strategy strategy){
this.strategy = strategy;
}
publicintexecuteDraw(int radius, int x, int y){
return strategy.draw(radius, x, y);
}
}
publicstaticvoidmain(String[] args) {
Context context = new Context(new BluePen()); // 使用綠色筆來(lái)畫
context.executeDraw(10, 0, 0);
}


觀察者模式
public classSubject{
private Listobservers = new ArrayList ();
private int state;
publicintgetState() {
return state;
}
publicvoidsetState(int state) {
this.state = state;
// 數(shù)據(jù)已變更,通知觀察者們
notifyAllObservers();
}
// 注冊(cè)觀察者
publicvoidattach(Observer observer) {
observers.add(observer);
}
// 通知觀察者們
publicvoidnotifyAllObservers() {
for (Observer observer : observers) {
observer.update();
}
}
}
public abstract classObserver{
protected Subject subject;
publicabstractvoidupdate();
}
public classBinaryObserverextendsObserver{
// 在構(gòu)造方法中進(jìn)行訂閱主題
publicBinaryObserver(Subject subject) {
this.subject = subject;
// 通常在構(gòu)造方法中將 this 發(fā)布出去的操作一定要小心
this.subject.attach(this);
}
// 該方法由主題類在數(shù)據(jù)變更的時(shí)候進(jìn)行調(diào)用
@Override
publicvoidupdate() {
String result = Integer.toBinaryString(subject.getState());
System.out.println("訂閱的數(shù)據(jù)發(fā)生變化,新的數(shù)據(jù)處理為二進(jìn)制值為:" + result);
}
}
public classHexaObserverextendsObserver{
publicHexaObserver(Subject subject) {
this.subject = subject;
this.subject.attach(this);
}
@Override
publicvoidupdate() {
String result = Integer.toHexString(subject.getState()).toUpperCase();
System.out.println("訂閱的數(shù)據(jù)發(fā)生變化,新的數(shù)據(jù)處理為十六進(jìn)制值為:" + result);
}
}
publicstaticvoidmain(String[] args) {
// 先定義一個(gè)主題
Subject subject1 = new Subject();
// 定義觀察者
new BinaryObserver(subject1);
new HexaObserver(subject1);
// 模擬數(shù)據(jù)變更,這個(gè)時(shí)候,觀察者們的 update 方法將會(huì)被調(diào)用
subject.setState(11);
}
訂閱的數(shù)據(jù)發(fā)生變化,新的數(shù)據(jù)處理為二進(jìn)制值為:1011
訂閱的數(shù)據(jù)發(fā)生變化,新的數(shù)據(jù)處理為十六進(jìn)制值為:B
責(zé)任鏈模式
如果產(chǎn)品給你這個(gè)需求的話,我想大部分人一開(kāi)始肯定想的就是,用一個(gè) List 來(lái)存放所有的規(guī)則,然后 foreach 執(zhí)行一下每個(gè)規(guī)則就好了。不過(guò),讀者也先別急,看看責(zé)任鏈模式和我們說(shuō)的這個(gè)有什么不一樣?
public abstract classRuleHandler{
// 后繼節(jié)點(diǎn)
protected RuleHandler successor;
publicabstractvoidapply(Context context);
publicvoidsetSuccessor(RuleHandler successor) {
this.successor = successor;
}
public RuleHandler getSuccessor() {
return successor;
}
}
public classNewUserRuleHandlerextendsRuleHandler{
publicvoidapply(Context context) {
if (context.isNewUser()) {
// 如果有后繼節(jié)點(diǎn)的話,傳遞下去
if (this.getSuccessor() != null) {
this.getSuccessor().apply(context);
}
} else {
throw new RuntimeException("該活動(dòng)僅限新用戶參與");
}
}
}
public classLocationRuleHandlerextendsRuleHandler{
publicvoidapply(Context context) {
boolean allowed = activityService.isSupportedLocation(context.getLocation);
if (allowed) {
if (this.getSuccessor() != null) {
this.getSuccessor().apply(context);
}
} else {
throw new RuntimeException("非常抱歉,您所在的地區(qū)無(wú)法參與本次活動(dòng)");
}
}
}
public classLimitRuleHandlerextendsRuleHandler{
publicvoidapply(Context context) {
int remainedTimes = activityService.queryRemainedTimes(context); // 查詢剩余獎(jiǎng)品
if (remainedTimes > 0) {
if (this.getSuccessor() != null) {
this.getSuccessor().apply(userInfo);
}
} else {
throw new RuntimeException("您來(lái)得太晚了,獎(jiǎng)品被領(lǐng)完了");
}
}
}
publicstaticvoidmain(String[] args) {
RuleHandler newUserHandler = new NewUserRuleHandler();
RuleHandler locationHandler = new LocationRuleHandler();
RuleHandler limitHandler = new LimitRuleHandler();
// 假設(shè)本次活動(dòng)僅校驗(yàn)地區(qū)和獎(jiǎng)品數(shù)量,不校驗(yàn)新老用戶
locationHandler.setSuccessor(limitHandler);
locationHandler.apply(context);
}
模板方法模式
public abstract classAbstractTemplate{
// 這就是模板方法
publicvoidtemplateMethod() {
init();
apply(); // 這個(gè)是重點(diǎn)
end(); // 可以作為鉤子方法
}
protectedvoidinit() {
System.out.println("init 抽象層已經(jīng)實(shí)現(xiàn),子類也可以選擇覆寫");
}
// 留給子類實(shí)現(xiàn)
protectedabstractvoidapply();
protectedvoidend() {
}
}
public classConcreteTemplateextendsAbstractTemplate{
publicvoidapply() {
System.out.println("子類實(shí)現(xiàn)抽象方法 apply");
}
publicvoidend() {
System.out.println("我們可以把 method3 當(dāng)做鉤子方法來(lái)使用,需要的時(shí)候覆寫就可以了");
}
}
publicstaticvoidmain(String[] args) {
AbstractTemplate t = new ConcreteTemplate();
// 調(diào)用模板方法
t.templateMethod();
}
狀態(tài)模式
public interfaceState{
publicvoiddoAction(Context context);
}
public classDeductStateimplementsState{
publicvoiddoAction(Context context) {
System.out.println("商品賣出,準(zhǔn)備減庫(kù)存");
context.setState(this);
//... 執(zhí)行減庫(kù)存的具體操作
}
public String toString() {
return "Deduct State";
}
}
public classRevertStateimplementsState{
publicvoiddoAction(Context context) {
System.out.println("給此商品補(bǔ)庫(kù)存");
context.setState(this);
//... 執(zhí)行加庫(kù)存的具體操作
}
public String toString() {
return "Revert State";
}
}
public classContext{
private State state;
private String name;
publicContext(String name) {
this.name = name;
}
publicvoidsetState(State state) {
this.state = state;
}
publicvoidgetState() {
return this.state;
}
}
publicstaticvoidmain(String[] args) {
// 我們需要操作的是 iPhone X
Context context = new Context("iPhone X");
// 看看怎么進(jìn)行補(bǔ)庫(kù)存操作
State revertState = new RevertState();
revertState.doAction(context);
// 同樣的,減庫(kù)存操作也非常簡(jiǎn)單
State deductState = new DeductState();
deductState.doAction(context);
// 如果需要我們可以獲取當(dāng)前的狀態(tài)
// context.getState().toString();
}
行為型模式總結(jié)
總結(jié)
更多精彩?
在公眾號(hào)【程序員編程】對(duì)話框輸入以下關(guān)鍵詞 查看更多優(yōu)質(zhì)內(nèi)容! 大數(shù)據(jù)?|?Java?|?1024?|?電子書?|?速查表? Python進(jìn)階?|?面試?|?手冊(cè)?|?成神?|?思想?|?小程序 命令行?|?人工智能?|?軟件測(cè)試?|?Web前端?|?Python 獲取更多學(xué)習(xí)資料
視頻 |?面試 |?技術(shù) | 電子書?
