本文内容为学习设计模式时的一些代码。整个代码可以运行。
接口
/**
* 水果接口
* @author guoyy
*
*/
public interface Fruit {
/**
* 展示方法
*/
public void show();
}
实现类
/**
* 桃子
* @author guoyy
*
*/
public class Peach implements Fruit {
@Override
public void show() {
System.out.println("桃子的颜色是红色");
}
}
/**
* 葡萄
* @author guoyy
*
*/
public class Grape implements Fruit {
@Override
public void show() {
System.out.println("葡萄的颜色是紫色");
}
}
工厂类
/**
* 水果工厂
* @author guoyy
*
*/
public class FruitFactory {
/**
* 根据传入的水果名称生产水果
* @param fruitName
* @return
*/
public Fruit getFruit(String fruitName) {
Fruit fruit = null;
if (fruitName == null || "".equals(fruitName)) {
return fruit;
}
if ("grape".equalsIgnoreCase(fruitName)) {
fruit = new Grape();
} else if ("peach".equalsIgnoreCase(fruitName)) {
fruit = new Peach();
}
return fruit;
}
/**
* 根据传入的水果类型生产水果
* @param clazz
* @return
*/
public Fruit createFruit(Class<? extends Fruit> clazz) {
Fruit fruit = null;
try {
fruit = (Fruit) Class.forName(clazz.getName()).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return fruit;
}
}
调用类
/**
* 调用
* @author guoyy
*
*/
public class FactoryPatternDemo {
public static void main(String[] args) {
FruitFactory fruitFactory = new FruitFactory();
Fruit peach = fruitFactory.getFruit("peach");
peach.show();
Fruit grape = fruitFactory.createFruit(Grape.class);
grape.show();
}
}
控制台输出:
桃子的颜色是红色
葡萄的颜色是紫色
总结:
工厂类中生产产品的方法最好用反射来生产,避免每增加一个产品类型就要修改生产产品的方法。