JavaOOP 实现墨盒颜色的多态案列

package hello5墨盒的颜色;

public class A4 implements Paper{

	@Override
	public String getSize() {
		
		return "A4";
	}

}
package hello5墨盒的颜色;

public class B5 implements Paper{

	@Override
	public String getSize() {
		// TODO 自动生成的方法存根
		return "B5";
	}

}
package hello5墨盒的颜色;

public class ColorInkBox implements InkBox{

	@Override
	public String getColor() {
		
		return "彩色";
	}

}
package hello5墨盒的颜色;

public class GrayInBox implements InkBox{

	@Override
	public String getColor() {
		
		return "黑白";
	}

}
package hello5墨盒的颜色;
/**
 * 墨盒的接口
 * @author Administrator
 *
 */
public interface InkBox {
	/**
	 * 得到墨盒的颜色
	 * @return
	 */
    String getColor();
}
package hello5墨盒的颜色;
/**
 * 纸张的接口
 * @author Administrator
 *
 */
public interface Paper {
	/**
	 * 得到纸张的大小
	 * @return
	 */
   String getSize();
}
package hello5墨盒的颜色;
/**
 * 打印机类
 * @author Administrator
 *
 */
public class Printer {
    InkBox inkBox;//墨盒
    Paper pePaper;//纸张
    /**
     * 设置打印机墨盒
     * @param inkBox
     */
	public void setInkBox(InkBox inkBox) {
		this.inkBox = inkBox;
	}
	/**
	 * 设置打印机纸张
	 * @param pePaper
	 */
	public void setPePaper(Paper pePaper) {
		this.pePaper = pePaper;
	}
    
	
	public void print(){
		System.out.println("使用"+inkBox.getColor()+"墨盒"+pePaper.getSize()+"纸张上打印.");
	}
}
package hello5墨盒的颜色;

public class Test {

	public static void main(String[] args) {
		//1定义打印机
		InkBox inkBox=null;
		Paper paper=null;
		Printer printer=new Printer();
		
		//使用黑白墨盒在A4纸张上打印
		inkBox=new GrayInBox();
		paper=new A4();
		printer.setInkBox(inkBox);
		printer.setPePaper(paper);
		printer.print();
		
		//使用彩色墨盒在B5上打印
		inkBox=new ColorInkBox();
		paper=new B5();
		printer.setInkBox(inkBox);
		printer.setPePaper(paper);
		printer.print();
		
		//使用彩色墨盒在A4纸张上打印
		inkBox=new ColorInkBox();
		paper=new A4();
		printer.setInkBox(inkBox);
		printer.setPePaper(paper);
		printer.print();

	}

}

你可能感兴趣的:(JavaOOP 实现墨盒颜色的多态案列)