先创建USB接口类
public interface Usb {
void service();
}
创建实现USB接口的使用类
public class Mouse implements Usb{
@Override
public void service() {
System.out.println("鼠标开始工作了.....");
}
}
==============================================
public class KeyBoard implements Usb{
@Override
public void service() {
System.out.println("键盘开始工作了...");
}
}
================================================
public class Upan implements Usb{
@Override
public void service() {
System.out.println("U盘开始工作了...");
}
}
......
创建USB工厂生产类
public class UsbFactory {
public static Usb createUsb(String type) {
Usb usb=null;
Class<?> class1=null;
try {
class1 = Class.forName(type);
usb=(Usb)class1.newInstance();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return usb;
}
}
创建usb.properties配置文件
1=com.qf.chap17_2.Mouse
2=com.qf.chap17_2.Fan
3=com.qf.chap17_2.Upan
4=com.qf.chap17_2.KeyBoard
5=com.qf.chap17_2.Mouse2
最后测试
public class Demo {
public static void main(String[] args) throws Exception{
System.out.println("=========请选择 1 鼠标 2风扇 3 u盘===========");
Scanner input=new Scanner(System.in);
String choice=input.next();
Properties properties=new Properties();
FileInputStream fis=new FileInputStream("src\\usb.properties");
properties.load(fis);
fis.close();
Usb usb=UsbFactory.createUsb(properties.getProperty(choice));
if(usb!=null) {
System.out.println("购买成功");
usb.service();
}else {
System.out.println("购买失败,您要购买的产品不存在");
}
}
}