小米(Mi)、海尔(Haier) 、TCL、都是数码家电制造商,它们都生产电视机 (Television)、空调(AirConditioner)、手机 (MobilePhone)。请用java设计一个系统,使用桥接模式,描述这家电制造商以及它们制造的电器。
时间: 2024-05-15 09:19:28 浏览: 182
我们可以先定义一个抽象类Electronics,包含生产商名称(brandName)和产品名称(productName)属性,以及一个抽象方法showInfo()用于展示电器的信息。
```java
public abstract class Electronics {
protected String brandName;
protected String productName;
public Electronics(String brandName, String productName) {
this.brandName = brandName;
this.productName = productName;
}
public abstract void showInfo();
}
```
然后我们可以定义具体的电器类,继承自Electronics类,如下:
```java
public class Television extends Electronics {
public Television(String brandName, String productName) {
super(brandName, productName);
}
@Override
public void showInfo() {
System.out.println("This is a " + brandName + " " + productName + " television.");
}
}
public class AirConditioner extends Electronics {
public AirConditioner(String brandName, String productName) {
super(brandName, productName);
}
@Override
public void showInfo() {
System.out.println("This is a " + brandName + " " + productName + " air conditioner.");
}
}
public class MobilePhone extends Electronics {
public MobilePhone(String brandName, String productName) {
super(brandName, productName);
}
@Override
public void showInfo() {
System.out.println("This is a " + brandName + " " + productName + " mobile phone.");
}
}
```
接下来我们可以定义一个桥接类Brand,包含一个Electronics类型的属性,以及一个showBrand()方法用于展示该品牌的所有电器信息。
```java
public class Brand {
protected Electronics electronics;
public Brand(Electronics electronics) {
this.electronics = electronics;
}
public void showBrand() {
electronics.showInfo();
}
}
```
最后,我们可以使用这些类组合出具体的电器品牌和产品:
```java
public class Main {
public static void main(String[] args) {
Electronics xiaomiTelevision = new Television("Xiaomi", "Mi TV 4S");
Electronics haierAirConditioner = new AirConditioner("Haier", "HSU-12LTC13/B1");
Electronics tclMobilePhone = new MobilePhone("TCL", "10 Pro");
Brand xiaomi = new Brand(xiaomiTelevision);
Brand haier = new Brand(haierAirConditioner);
Brand tcl = new Brand(tclMobilePhone);
xiaomi.showBrand();
haier.showBrand();
tcl.showBrand();
}
}
```
输出结果:
```
This is a Xiaomi Mi TV 4S television.
This is a Haier HSU-12LTC13/B1 air conditioner.
This is a TCL 10 Pro mobile phone.
```
阅读全文