解决方案:使用桥接模式
具体的手机类实现接口
package com.lesson8.bridge; /** * @author 朝花不迟暮 * @version 1.0 * @date 2020/8/29 21:40 */ public class Vivo implements Brand { @Override public void open() { System.out.println("vivo手机开机!"); } @Override public void close() { System.out.println("vivo手机关机!"); } @Override public void call() { System.out.println("vivo手机打电话!"); } } package com.lesson8.bridge; /** * @author 朝花不迟暮 * @version 1.0 * @date 2020/8/29 21:39 */ public class XiaoMi implements Brand { @Override public void open() { System.out.println("小米手机开机!"); } @Override public void close() { System.out.println("小米手机关机!"); } @Override public void call() { System.out.println("小米手机打电话!"); } }抽象类,把接口聚合进来
package com.lesson8.bridge; /** * @author 朝花不迟暮 * @version 1.0 * @date 2020/8/29 21:41 */ public abstract class Phone { private Brand brand; public Phone(Brand brand) { this.brand = brand; } protected void open() { this.brand.open(); } protected void close() { this.brand.close(); } protected void call() { this.brand.call(); } }不同种类的手机
package com.lesson8.bridge; /** * @author 朝花不迟暮 * @version 1.0 * @date 2020/8/29 21:43 */ public class FoldedPhone extends Phone { public FoldedPhone(Brand brand) { super(brand); } @Override protected void open() { super.open(); System.out.println("折叠手机样式"); } @Override protected void close() { super.close(); System.out.println("折叠手机样式"); } @Override protected void call() { super.call(); System.out.println("折叠手机样式"); } } package com.lesson8.bridge; /** * @author 朝花不迟暮 * @version 1.0 * @date 2020/8/29 21:56 */ public class UpRightPhone extends Phone { public UpRightPhone(Brand brand) { super(brand); } @Override protected void open() { super.open(); System.out.println("滑盖手机样式"); } @Override protected void close() { super.close(); System.out.println("滑盖手机样式"); } @Override protected void call() { super.call(); System.out.println("滑盖手机样式"); } }客户端
package com.lesson8.bridge; /** * @author 朝花不迟暮 * @version 1.0 * @date 2020/8/29 21:50 */ public class Client { public static void main(String[] args) { Phone phone = new FoldedPhone(new XiaoMi()); phone.open(); phone.call(); phone.close(); System.out.println("-------------------------------------------"); Phone phone2 = new FoldedPhone(new Vivo()); phone2.open(); phone2.call(); phone2.close(); System.out.println("-------------------------------------------"); Phone phone3 = new UpRightPhone(new XiaoMi()); phone3.open(); phone3.call(); phone3.close(); System.out.println("-------------------------------------------"); Phone phone4 = new UpRightPhone(new Vivo()); phone4.open(); phone4.call(); phone4.close(); } }对于那些不希望使用继承或因为多层次继承导致系统类的个数急剧增加的系统,桥接模式及其适用。比如银行转账系统、消息管理