桥接模式
品牌接口
interface Brand{
void open();
void call();
void close();
}
不同品牌的实现类
class Xiaomi implements Brand{
@Override
public void open() {
System.out.println("小米手机开机");
}
@Override
public void call() {
System.out.println("小米手机打电话");
}
@Override
public void close() {
System.out.println("小米手机关机");
}
}
class Vivo implements Brand{
@Override
public void open() {
System.out.println("Vivo手机开机");
}
@Override
public void call() {
System.out.println("Vivo手机打电话");
}
@Override
public void close() {
System.out.println("Vivo手机关机");
}
}
手机的抽象类
abstract class Phone{
private Brand brand;
public Phone(Brand brand) {
this.brand = brand;
}
protected void open(){
this.brand.open();
}
protected void call(){
this.brand.call();
}
protected void close(){
this.brand.close();
}
}
不同类型的手机类
class FoldePhone extends Phone{
public FoldePhone(Brand brand) {
super(brand);
}
public void open(){
super.open();
System.out.println(" 翻盖手机 ");
}
public void call(){
super.call();
System.out.println(" 翻盖手机 ");
}
public void close(){
super.close();
System.out.println(" 翻盖手机 ");
}
}
class UprightPhone extends Phone{
public UprightPhone(Brand brand) {
super(brand);
}
public void open(){
super.open();
System.out.println(" 直立手机 ");
}
public void call(){
super.call();
System.out.println(" 直立手机 ");
}
public void close(){
super.close();
System.out.println(" 直立手机 ");
}
}
测试类
public class BrandTest {
public static void main(String[] args) {
FoldePhone foldePhone = new FoldePhone(new Xiaomi());
foldePhone.open();
foldePhone.call();
foldePhone.close();
UprightPhone uprightPhone = new UprightPhone(new Vivo());
uprightPhone.open();
uprightPhone.call();
uprightPhone.close();
}
}