package com.test.design.bridge;
public abstract class Task {
//任务需求
public abstract void requirement();
//任务进度
public abstract void progress();
}
package com.test.design.bridge;
public class Task1 extends Task {
@Override
public void progress() {
System.out.println("任务一正在按进度进行。。。。");
}
@Override
public void requirement() {
System.out.println("任务一的需求是这样的。。。。");
}
}
package com.test.design.bridge;
public class Task2 extends Task {
@Override
public void progress() {
System.out.println("任务二正在按进度进行。。。。");
}
@Override
public void requirement() {
System.out.println("任务二的需求是这样的。。。。");
}
}
package com.test.design.bridge;
public abstract class Worker {
private Task task;
public Worker(Task task){
this.task = task;
}
public void finishTask(){
this.task.requirement();
this.task.progress();
}
}
package com.test.design.bridge;
public class Worker1 extends Worker {
public Worker1(Task1 task) {
super(task);
}
@Override
public void finishTask() {
super.finishTask();
System.out.println("任务一完成喽,开心中...");
}
}
package com.test.design.bridge;
public class WorkerAll extends Worker {
public WorkerAll(Task task) {
super(task);
}
@Override
public void finishTask() {
super.finishTask();
System.out.println("任务完成了...");
}
}
package com.test.design.bridge;
public class Boss {
public static void main(String[] args) {
Task1 task1 = new Task1();
Worker1 worker1 = new Worker1(task1);
worker1.finishTask();
System.out.println("");
Task2 task2 = new Task2();
WorkerAll workerAll = new WorkerAll(task2);
workerAll.finishTask();
System.out.println("");
workerAll = new WorkerAll(task1);
workerAll.finishTask();
}
}
桥梁模式有两个角色:业务抽象角色和业务实现角色,业务抽象角色引用业务实现角色,或者说业务抽象角色的部分实现是由业务实现角色完成的。桥梁模式的优点就是类间解耦,像上面那样,两个角色(task、worker)都可以自己的扩展下去,不会相互影响,这个也符合OCP 原则。