接口定义类
IinkBox.java
package printerDemo.iface;
public interface IInkBox {
public String getColor();
}
IPaper.java
package printerDemo.iface;
public interface IPaper {
String getSize();
}
接口实现类
A4PaperImpl.java
package printerDemo.impl;
import printerDemo.iface.IPaper;
public class A4PaperImpl implements IPaper{
@Override
public String getSize() {
return "A4";
}
}
B5PaperImpl.java
package printerDemo.impl;
import printerDemo.iface.IPaper;
public class B5PaperImpl implements IPaper{
@Override
public String getSize() {
return "B5";
}
}
ColorInkBoxImpl.java
package printerDemo.impl;
import printerDemo.iface.IInkBox;
public class ColorInkBoxImpl implements IInkBox{
@Override
public String getColor() {
return "红色";
}
}
核心“业务”类
Printer.java
核心“业务”类
package printerDemo;
import printerDemo.iface.IInkBox;
import printerDemo.iface.IPaper;
public class Printer {
private IInkBox inkBox = null;
private IPaper paper = null;
public void print(String content) {
if(null == inkBox || null == paper) {
System.out.println("墨盒和纸张出现错误");
return;
}
String color = inkBox.getColor();
String type = paper.getSize();
System.out.println("以下文字是" + color + "色的");
System.out.println("使用纸张:" + type);
System.out.println("打印内容:" + content);
}
public IInkBox getInkBox() {
return inkBox;
}
public void setInkBox(IInkBox inkBox) {
this.inkBox = inkBox;
}
public IPaper getPaper() {
return paper;
}
public void setPaper(IPaper paper) {
this.paper = paper;
}
}
PrinterTest.java
主函数
package printerDemo;
import printerDemo.impl.A4PaperImpl;
import printerDemo.impl.B5PaperImpl;
import printerDemo.impl.ColorInkBoxImpl;
public class PrinterTest {
public static void main(String[] args) {
Printer printer = new Printer();
printer.setInkBox(new ColorInkBoxImpl());
printer.setPaper(new A4PaperImpl());
printer.print("测试内容");
printer.setPaper(new B5PaperImpl());
printer.print("测试内容");
}
}