桥接模式
2017-07-19 本文已影响0人
会思考的鸭子
未使用桥接模式

问题
- 扩展性问题
如果要增加一个新的类型如手机,则要增加多个品牌下的类 - 违反单一职责原则
一个类:如联想笔记本,有两个引起这个类变化的原因
使用桥接模式
-
UML
image.png
-
代码实现
package com.amberweather.bridge;
/**
* 机器类型
* @author Administrator
*
*/
public class Computer {
protected Brand brand;
public Computer(Brand brand) {
super();
this.brand = brand;
}
public void sale(){
brand.sale();
}
}
class Desktop extends Computer{
public Desktop(Brand brand){
super(brand);
}
public void sale(){
brand.sale();
System.out.println("销售台式机");
}
}
class Laptop extends Computer{
public Laptop(Brand brand){
super(brand);
}
public void sale(){
brand.sale();
System.out.println("销售笔记本");
}
}
package com.amberweather.bridge;
/**
* 品牌
* @author Administrator
*
*/
public interface Brand{
void sale();
}
class Lenovo implements Brand{
public void sale(){
System.out.println("销售联想");
}
}
class Dell implements Brand{
public void sale(){
System.out.println("销售戴尔");
}
}
package com.amberweather.bridge;
public class Client {
public static void main(String[] args) {
Computer c = new Laptop(new Dell());
c.sale();
}
}
