定义墨盒接口类:
```javapackage com.hnpi.demo;/*** 墨盒接口*/public interface InkBox {public void ink();}
实现墨盒接口类,具体数据自己看着添加,这里只写了彩色和黑色
package com.hnpi.demo;/*** 彩色墨盒*/public class ColorBox implements InkBox {@Overridepublic void ink() {System.out.print("彩色墨盒");}}
package com.hnpi.demo;/*** 黑色墨盒*/public class BlackBox implements InkBox {@Overridepublic void ink() {System.out.print("黑色墨盒");}}
定义纸张接口:
package com.hnpi.demo;/*** 纸张接口*/public interface Pager {public void pager();}
实现纸张接口类,具体数据自己看着添加,这里只写了A4和B5两种
package com.hnpi.demo;/*** A4纸*/public class A4Pager implements Pager {@Overridepublic void pager() {System.out.println("A4纸");}}
package com.hnpi.demo;/*** B5纸*/public class B5Pager implements Pager {@Overridepublic void pager() {System.out.println("B5纸");}}
定义打印机类:
package com.hnpi.demo;import java.awt.print.Paper;public class Printer {private InkBox ink;private Pager paper;public Printer(InkBox ink,Pager pager){super();this.ink = ink;this.paper = pager;}public void print(){ink.ink();System.out.print(":");paper.pager();System.out.println("打印机开始工作");}}
写一个测试类测试下写的能不能运行
package com.hnpi.test;import com.hnpi.demo.*;public class Test1 {public static void main(String[] args) {ColorBox color = new ColorBox();BlackBox black = new BlackBox();A4Pager A4 = new A4Pager();B5Pager B5 = new B5Pager();Printer printer=new Printer(color, A4);printer.print();}}
运行一下看能不能成功
运行成功,OK。