定义
任何可以产生对象的方法或类,都可以称之为工厂
单例也是一种工厂
为什么有了new之后,还要有工厂?
- 灵活控制生产过程
- 权限、修饰、日志…
不使用工厂模式
package com.company;
interface IFood{ //定义一个食物标准
public void eat(); //吃
}
class Bread implements IFood{
@Override
public void eat() {
System.out.println("吃面包。");
}
}
class Milk implements IFood{
@Override
public void eat() {
System.out.println("喝牛奶。");
}
}
//接口、抽象类
public class Main {
public static void main(String[] args) {
IFood food = new Bread();
food.eat();
IFood milk = new Milk();
milk.eat();
}
}
此时的程序出现有耦合的问题,而造成耦合最直接的元凶:“关键字new”。良好的设计应该避免耦合。
使用工厂模式
静态工厂
package com.company;
interface IFood{ //定义一个食物标准
public void eat(); //吃
}
class Bread implements IFood{
@Override
public void eat() {
System.out.println("吃面包。");
}
}
class Milk implements IFood{
@Override
public void eat() {
System.out.println("喝牛奶。");
}
}
class Factory{
public static IFood getInstance(String className) {
if("bread".equals(className)){
return new Bread();
}else if("milk".equals(className)){
return new Milk();
}else{
return null;
}
}
}
//接口、抽象类
public class Main {
public static void main(String[] args) {
IFood food = Factory.getInstance("milk");
if(food != null) food.eat();
}
}
动态工厂(通过反射)
package newinstance;
interface IFood{ //定义一个食物标准
public void eat(); //吃
}
class Bread implements IFood{
@Override
public void eat() {
System.out.println("吃面包。");
}
}
class Milk implements IFood{
@Override
public void eat() {
System.out.println("喝牛奶。");
}
}
class Factory{
public static IFood getInstance(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
IFood iFood = null;
Class<?> cls = Class.forName(className);
iFood = (IFood)cls.newInstance();
return iFood;
}
}
//接口、抽象类
public class JavaAPIDemo2 {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
IFood food = Factory.getInstance("newinstance.Milk");
if(food != null) food.eat();
}
}
使用泛型改造动态工厂
此时的工厂设计模式不再受限于指定的接口,可以为所有接口提供服务
package newinstance;
interface IFood{ //定义一个食物标准
public void eat(); //吃
}
class Bread implements IFood{
@Override
public void eat() {
System.out.println("吃面包。");
}
}
class Milk implements IFood{
@Override
public void eat() {
System.out.println("喝牛奶。");
}
}
class Factory{
@SuppressWarnings("unchecked")
public static <T> T getInstance(String className, Class<T> clazz) throws Exception {
T instance = (T) Class.forName(className).getDeclaredConstructor().newInstance();
return instance;
}
}
public class JavaAPIDemo2 {
public static void main(String[] args) throws Exception {
IFood milk = Factory.getInstance("newinstance.Milk", Milk.class);
if (milk != null) {
milk.eat();
}
IFood bread = Factory.getInstance("newinstance.Bread", Bread.class);
if (bread != null) {
bread.eat();
}
}
}