1. 程式人生 > >不同品牌電腦和不同種類介面搭配(橋接模式)

不同品牌電腦和不同種類介面搭配(橋接模式)

問題

聯想、戴爾等品牌電腦,搭配USB介面實現各種功能,隨著技術突破,可能不支援USB介面了,比如支援新的USB type C介面等

解決方案

橋接模式

UML類圖

在這裡插入圖片描述

原始碼

package task2;

public interface Adapter {
	public abstract void use(String computerBrand);
}

package task2;

public class Usb implements Adapter{

	@Override
	public void use(String computerBrand) {
		System.out.println("The "+computerBrand+" uses "+"USB.");
	}

}

package task2;

public class Thunderbolt implements Adapter{

	@Override
	public void use(String computerBrand) {
		System.out.println("The "+computerBrand+" uses "+"Thunderbolt.");
	}

}

package task2;

public abstract class Computer {

		protected Adapter adapter;
		public void setAdapter(Adapter adapter) {
			this.adapter = adapter;
		}
		public abstract void use();
}

package task2;

public class Asus extends Computer{

	@Override
	public void use() {
		String computerBrand = "ASUS";
		this.adapter.use(computerBrand);
	}
	
}

package task2;

public class Lenovo extends Computer{

	@Override
	public void use() {
		String computerBrand = "Levono";
		this.adapter.use(computerBrand);
	}
	
}

package task2;

public class Acer extends Computer{

	@Override
	public void use() {
		String computerBrand = "Acer";
		this.adapter.use(computerBrand);
	}
	
}

測試及結果

package task2;

public class Client {
	public static void main(String[] args) {
		Adapter adapter = new Usb();
		Computer computer = new Lenovo();
		
		computer.setAdapter(adapter);
		computer.use();
	}
}

在這裡插入圖片描述