某打印中心既有黑白打印机,也有彩色打印机,在打印时,使用不同的打印机,打印的效果也就不同,采用面向接口的思想编写实现打印中心的功能。在一个程序中实现
时间: 2023-12-20 13:07:35 浏览: 25
以下是使用面向接口思想编写实现打印中心的示例代码:
```java
// 定义打印机接口
public interface Printer {
void print(String content);
}
// 实现黑白打印机类
public class BlackWhitePrinter implements Printer {
@Override
public void print(String content) {
System.out.println("使用黑白打印机打印:" + content);
}
}
// 实现彩色打印机类
public class ColorPrinter implements Printer {
@Override
public void print(String content) {
System.out.println("使用彩色打印机打印:" + content);
}
}
// 定义打印中心类
public class PrintCenter {
private Printer printer;
// 构造函数注入打印机类
public PrintCenter(Printer printer) {
this.printer = printer;
}
// 打印方法
public void print(String content) {
printer.print(content);
}
}
// 测试代码
public class Main {
public static void main(String[] args) {
// 使用黑白打印机打印
Printer blackWhitePrinter = new BlackWhitePrinter();
PrintCenter printCenter = new PrintCenter(blackWhitePrinter);
printCenter.print("这是一份黑白打印的文档");
// 使用彩色打印机打印
Printer colorPrinter = new ColorPrinter();
printCenter = new PrintCenter(colorPrinter);
printCenter.print("这是一份彩色打印的文档");
}
}
```
通过定义打印机接口和不同的打印机实现类,可以方便地扩展和修改打印中心的功能。在打印中心类中,使用构造函数注入打印机类,实现了打印机的动态切换。在测试代码中,可以看到不同打印机的使用效果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)