未使用橋接模式

image.png
問題
- 擴(kuò)展性問題
如果要增加一個(gè)新的類型如手機(jī),則要增加多個(gè)品牌下的類 - 違反單一職責(zé)原則
一個(gè)類:如聯(lián)想筆記本,有兩個(gè)引起這個(gè)類變化的原因
使用橋接模式
-
UML
image.png 代碼實(shí)現(xiàn)
package com.amberweather.bridge;
/**
* 機(jī)器類型
* @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("銷售臺(tái)式機(jī)");
}
}
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("銷售聯(lián)想");
}
}
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();
}
}

image.png
