设计模式--工厂模式(工厂方法模式)

工厂模式也称为简单工厂模式,是一种创建型设计模式,这种设计模式提供按照需要创建对象的最佳方式。
但是这种方式不会对外暴露创建细节,具有统一的接口创建所需对象。
这种模式其实就是为了给代码结构提供扩展性,屏蔽每一个功能类中的具体实现逻辑。便于外部,更加简单的调用,而且能去掉众多的if…else。
但是这种方式需要实现的类比较多、难以维护、开发成功高。
但是这种可以通过结合多种设计模式逐步优化。

请看下面例子:

  1. 接口类
public interface IInterface {/*** 接口定义* @param a* @param b*/void add(String a,String b);
}
  1. 接口实现类
// 实现类1
public class IInterfaceImplONE implements IInterface {@Overridepublic void add(String a, String b) {System.out.println("这是IInterface的第一个实现。。,入参为:" + a + "," + b);}
}//实现类2
public class IInterfaceImplTWO implements IInterface {@Overridepublic void add(String a, String b) {System.out.println("这是IInterface的第二个实现。。,入参为:" + a + "," + b);}
}
  1. 工厂类
public class Ifactory {/*** 类型方式实例化* @param serviceType 服务类型* @return 实例化对象*/public IInterface getService(Integer serviceType){if (null == serviceType) return null;if (1 == serviceType) return new IInterfaceImplONE();if (2 == serviceType) return new IInterfaceImplTWO();throw new RuntimeException("不存在。。。");}/*** 服务类信息方式实例化* @param clazz 服务类型* @return 实例化对象* @throws InstantiationException* @throws IllegalAccessException*/public IInterface getService(Class<? extends IInterface> clazz) throws InstantiationException, IllegalAccessException {if (null == clazz) return null;return clazz.newInstance();}
}
  1. 测试方法
public class TestEasyFactory {public static void main(String[] args) {Ifactory ifactory = new Ifactory();IInterface service1 = ifactory.getService(1);service1.add("呵呵","哈哈");IInterface service2 = ifactory.getService(2);service2.add("啦啦","飒飒");//第二种实例化方式,这里就不写了,很简单。}
}/*
> Task :TestEasyFactory.main()
这是IInterface的第一个实现。。,入参为:呵呵,哈哈
这是IInterface的第二个实现。。,入参为:啦啦,飒飒
*/