本文共 2225 字,大约阅读时间需要 7 分钟。
1、使用桥接模式,将多个维度分开管理,减去多层继承的繁琐,客户端可以直接采用自由组合方式选择调用,多个维度的变化互不影响。对比未使用桥接模式,电脑接口中直接管理两个职责(品牌[联想、戴尔、华硕]、种类[台式、笔记本、平板]),背离SRP设计原则
2、代码演示如下:
package com.tiger.bridge;/** * 管理品牌维度[联想、戴尔、华硕、...] * @author tiger * @Date 2017年9月3日 */public interface Brand { void sale();}class Lenovo implements Brand{ @Override public void sale() { System.out.print("联想"); }}class Dell implements Brand{ @Override public void sale() { System.out.print("戴尔"); }}class Shengzhou implements Brand{ @Override public void sale() { System.out.print("神舟"); }}package com.tiger.bridge;/** * 管理电脑种类的维度[台式、笔记本、平板、...] * @author tiger * @Date 2017年9月3日 */public abstract class Computer { //品牌是电脑的固有属性,不管是台式机,还是笔记本都具有品牌属性 protected Brand brand; /** * 当不设置电脑品牌时,默认是联想电脑 * @param brand */ public Computer() { this.brand = new Lenovo(); } /** * 电脑品牌构建 * @param brand */ public Computer(Brand brand) { this.brand = brand; } /** * 设置电脑品牌属性 * @param brand */ public void setBrand(Brand brand) { this.brand = brand; } public abstract void sale();}/** * 台式电脑 * @author tiger * @Date 2017年9月3日 */class Desktop extends Computer{ public Desktop() {} public Desktop(Brand brand) { super(brand); } @Override public void sale() { brand.sale(); System.out.println("台式机"); }}/** * 笔记本电脑 * @author tiger * @Date 2017年9月3日 */class Laptop extends Computer{ public Laptop() {} public Laptop(Brand brand) { super(brand); } @Override public void sale() { brand.sale(); System.out.println("笔记本"); }}/** * 平板电脑 * @author tiger * @Date 2017年9月3日 */class Pad extends Computer{ public Pad() {} public Pad(Brand brand) { super(brand); } @Override public void sale() { brand.sale(); System.out.println("平板"); }}package com.tiger.bridge;/** * 使用桥接模式,将多个维度分开管理,减去多层继承的繁琐,客户端可以直接采用自由组合方式选择调用,多个维度的变化互不影响。 * 对比未使用桥接模式,电脑接口中直接管理两个职责(品牌[联想、戴尔、华硕]、种类[台式、笔记本、平板]),背离SRP设计原则 * @author tiger * @Date 2017年9月3日 */public class Client { public static void main(String[] args) { //客户表示想买联想台式机 Computer computer = new Desktop(new Lenovo()); computer.sale(); //客户表示想买戴尔平板电脑 Brand brand = new Dell(); Computer computer2 = new Pad(brand); computer2.sale(); //当客户不选择品牌时,默认是联想 Computer computer3 = new Desktop();// computer3.setBrand(new Dell()); computer3.sale(); }}
转载地址:http://gceof.baihongyu.com/