桥接模式(Bridge Pattern)把抽象与具体实现进行解耦,主要针对一个角色有多种分类的情况,可以减少了对实例的依赖,通过桥接和抽象类建立一个关联,特别适合两个独立变化的维度之间的桥接。
一、需求举例:
一个团队的Leader,负责运行团队,团队内有初级工程师,中级工程师和高级工程师。团队的Leader向各级工程师分配任务。
二、类图:
三、代码实例:
1.工程师父接口:Engineer
package com.lance.bridge;
public interface Engineer {
default void develop(String program) {
System.out.println("Engineer default refuse " + program);
}
}
2.初级工程师类:JuniorEngineer
package com.lance.bridge;
public class JuniorEngineer implements Engineer {
@Override
public void develop(String program) {
System.out.println("Junior Engineer develop " + program);
}
}
3.中级工程师:IntermediateEngineer
package com.lance.bridge;
public class IntermediateEngineer implements Engineer {
@Override
public void develop(String program) {
System.out.println("Intermediate Engineer develop " + program);
}
}
4.高级工程师类:SeniorEngineer
package com.lance.bridge;
public class SeniorEngineer implements Engineer {
@Override
public void develop(String program) {
System.out.println("Senior Engineer develop " + program);
}
}
5.领导父类:Leader
package com.lance.bridge;
public abstract class Leader {
protected Engineer engineer;
public Leader(Engineer engineer) {
this.engineer = engineer;
}
public abstract void run(String program);
}
6.团队领导:TeamLeader
package com.lance.bridge;
public class TeamLeader extends Leader {
public TeamLeader(Engineer engineer) {
super(engineer);
}
@Override
public void run(String program) {
engineer.develop(program);
}
}
7.主类:BridgePattern
package com.lance.bridge;
public class BridgePattern {
public static void main(String[] args) {
System.out.println("==========start==========");
Leader leader = new TeamLeader(new JuniorEngineer());
leader.run("[easy program]");
System.out.println("=======================");
leader = new TeamLeader(new IntermediateEngineer());
leader.run("[middle program]");
System.out.println("=======================");
leader = new TeamLeader(new JuniorEngineer());
leader.run("[difficult program]");
System.out.println("==========end==========");
}
}
输出结果:
==========start==========
Junior Engineer develop [easy program]
=======================
Intermediate Engineer develop [middle program]
=======================
Junior Engineer develop [difficult program]
==========end==========
网友评论