一、建立打印接口
//Print接口 Print.java
package jkuse;
interface Print {
public void open();
public void close();
public void print(String s);
public void open();
public void close();
public void print(String s);
}
二、建立HP子类、CN子类及其对接口方法的对应实现
//HP.java
package jkuse;
public class HP implements Print {
public void open() {
System.out.println(“HP open!!!”);
};
public void close() {
System.out.println(“HP close!!!”);
};
public void print(String s) {
System.out.println(“HP–print>>”+ s);
};
public void open() {
System.out.println(“HP open!!!”);
};
public void close() {
System.out.println(“HP close!!!”);
};
public void print(String s) {
System.out.println(“HP–print>>”+ s);
};
}
//CN.java
package jkuse;
public class CN implements Print {
public void open() {
System.out.println(“CN open!!!”);
};
public void close() {
System.out.println(“CN close!!!”);
};
public void print(String s) {
System.out.println(“CN–print>>”+ s);
};
public void open() {
System.out.println(“CN open!!!”);
};
public void close() {
System.out.println(“CN close!!!”);
};
public void print(String s) {
System.out.println(“CN–print>>”+ s);
};
}
三、设计工厂类用于将要实现的对对象的生产进行选择,将此做法封装于方法中
//factory.java
package jkuse;
public class factory {
public static Print getPrint(int flag) {
Print print = null;
if (flag == 0) {
print = new HP();
}
else if(flag== 1) {
print = new CN();
}
else if(flag == 2) {
print =new CCB();
}
return print;
}
public static Print getPrint(int flag) {
Print print = null;
if (flag == 0) {
print = new HP();
}
else if(flag== 1) {
print = new CN();
}
else if(flag == 2) {
print =new CCB();
}
return print;
}
}
四、用户类的测试
//user.java
package jkuse;
public class user {
public static void main(String args[]) {
public static void main(String args[]) {
int flag =2;
Print print = factory.getPrint(flag);//调用工厂类的选择方法
print .open();
print.print(“老大好!”);
print.close();
}
}
版权声明:本文为BuGengFeng原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。