【java】工厂模式Factory,利用反射改进

时间:2022-07-03 00:43:43
 package 反射;
interface Product{
public void produce();
}
class socks implements Product{
@Override
public void produce() {
System.out.println("袜子被生产");
}
}
/*
class shoes implements Product{
@Override
public void produce() {
System.out.println("鞋子被生产");
}
}
*/
class Factory{
private static Product product;
public static Product getInstance(String productName){
if(productName.equals("袜子"))
product=new socks();
/*每添加一个产品就得增加getInstance方法的代码,可以利用反射改写
if(productName.equals("鞋子"))
product=new shoes();
*/
return product;
}
}
public class TestFactory {
public static void main(String[] args) {
Product product=Factory.getInstance("袜子");
product.produce();//袜子被生产
/*
Product product2=Factory.getInstance("鞋子");
product2.produce();//鞋子被生产
*/
}
}

此代码含new耦合,有待优化。

 package 反射;
interface Product{
public void produce();
}
class socks implements Product{
@Override
public void produce() {
System.out.println("袜子被生产");
}
} class shoes implements Product{
@Override
public void produce() {
System.out.println("鞋子被生产");
}
} class Factory{
private static Product product;
public static Product getInstance(String productName) throws ClassNotFoundException, InstantiationException, IllegalAccessException{
Class<?> cls=Class.forName(productName);
product=(Product)cls.newInstance();
return product;
}
}
public class TestFactory {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
Product product=Factory.getInstance("反射.socks");
product.produce();//袜子被生产 Product product2=Factory.getInstance("反射.shoes");
product2.produce();//鞋子被生产 }
}

利用反射改进