设计模式之桥(bridge)
程序员文章站
2022-07-04 08:44:18
...
将抽象部分与它的实现部分分离,使之都可以独立的变化。
AbstractLogImpl 与 AbstractLog即构成日志与平台之间的桥梁,实现日志与平台的多种组合。 public class Bridge { // 日志 abstract class AbstractLog { protected AbstractLogImpl abstractLogImpl; public void setAbstractLogImpl(AbstractLogImpl abstractLogImpl) { this.abstractLogImpl = abstractLogImpl; } public abstract void printLog(); } class DbLog extends AbstractLog { public void printLog() { abstractLogImpl.runPlatform(); System.out.println("dabase log..."); } } class FileLog extends AbstractLog { public void printLog() { abstractLogImpl.runPlatform(); System.out.println("file log..."); } } // 平台 abstract class AbstractLogImpl { abstract void runPlatform(); } class Windows extends AbstractLogImpl { public void runPlatform() { System.out.println("run in windows"); } } class Linux extends AbstractLogImpl { public void runPlatform() { System.out.println("run in linux"); } } public static void main(String[] args){ Bridge bridge = new Bridge(); AbstractLog al = bridge.new DbLog(); AbstractLogImpl ali = bridge.new Windows(); al.setAbstractLogImpl(ali); //平台与日志组合windows与dblog al.printLog(); } }