工厂模式:定义一个用于创建对象的借口,让子类决定实例化哪一个类
UML图示:
代码示例:
/**
* Created by nevenon 2017/9/12.
*/
public class MobileCompany {
public void main(String[] args[]){
AbstractProductFactory factory = new PhoneFactory();
factory.createPhone(XiaoMi.class);
factory.createPhone(HuaWei.class);
}
}
interface Phone{
public void call();
}
class XiaoMi implements Phone{
@Override
public void call(){
System.out.println("我是XiaoMi手机");
}
}
class HuaWei implements Phone{
@Override
public void call() {
System.out.println("我是HuaWei手机");
}
}
interface AbstractProductFactory{
public <T extends Phone> T createPhone(Class<T> c);
}
class PhoneFactory implements AbstractProductFactory{
@Override
public <T extends Phone> T createPhone(Class<T> c) {
try {
Phone phone = (Phone) forName(c.getName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
}