某打印中心既有黑白打印机,也有彩色打印机,在打印时,使用不同的打印机,打印的效果也就不同,采用面向接口的思想编写实现打印中心的功能。
时间: 2023-11-11 09:03:19 浏览: 64
首先,我们需要定义一个打印接口(Printer),该接口包括一个打印方法(print),用于执行打印操作。接着,我们可以定义两个实现类,分别是黑白打印机(BlackWhitePrinter)和彩色打印机(ColorPrinter),这两个类都实现了打印接口(Printer)。具体实现如下:
```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);
}
}
```
接下来,我们可以定义一个打印中心(PrintCenter)类,这个类包含一个打印方法,通过传入不同的打印机实例,可以实现不同打印效果:
```java
public class PrintCenter {
private Printer printer;
public void setPrinter(Printer printer) {
this.printer = printer;
}
public void print(String content) {
printer.print(content);
}
}
```
最后,我们可以通过如下代码使用打印中心:
```java
PrintCenter printCenter = new PrintCenter();
//使用黑白打印机打印
printCenter.setPrinter(new BlackWhitePrinter());
printCenter.print("这是一份黑白打印文件");
//使用彩色打印机打印
printCenter.setPrinter(new 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)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)