Fan.java
public class Fan implements Usb {
@Override
public void service() {
System.out.println("风扇开始工作...");
}
}
Mouse.java
public class Mouse implements Usb {
@Override
public void service() {
System.out.println("mouse 开始工作了...");
}
}
Upan.java
public class Upan implements Usb {
@Override
public void service() {
System.out.println("Uapn 开始工作了 ...");
}
}
Usb.java
/**
* 父类产品
*/
public interface Usb {
void service();
}
UsbFactory.java
/**
* 工厂类
*/
public class UsbFactory {
public static Usb createUsb(String type) { // 创建类型的全名称 带包名。 com.qf.
Usb usb = null;
Class<?> class1;
try {
class1 = Class.forName(type);
usb = (Usb) class1.newInstance();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return usb;
}
}
Demo.java
/**
* 客户端
*/
public class Demo {
public static void main(String[] args) throws IOException {
System.out.println("1. 鼠标,2,风扇,3,U盘");
Scanner input = new Scanner(System.in);
String choice = input.next();
ClassPathResource classPathResource = new ClassPathResource("/properties/usb.properties");
InputStream inputStream =classPathResource.getInputStream();
Properties properties = new Properties();
properties.load(new InputStreamReader(inputStream, "UTF-8"));
Usb usb = UsbFactory.createUsb(properties.getProperty(choice));
if (usb != null) {
System.out.println("购买成功");
usb.service();
} else {
System.out.println("您购买的产品不存在。");
}
}
}
运行:
1. 鼠标,2,风扇,3,U盘
1 // 此处为输入
购买成功
mouse 开始工作了...
usb.properties路径:
properties/usb.properties