工厂模式给我的感受就是在,其思想就是解耦。不用像以前写代码自己new一个一个的对象,然后再去调方法。而是,通过面向接口编程,屏蔽掉其内部的细节,使得调用者不用直接去一个一个的new对象再去维护。
只管面向接口去调用,里面细节对使用者透明。实现了创建者和调用者分离。
工厂模式细分有3种:
- 静态工厂模式
- 工厂模式
- 抽象工厂
初学,由于水平有限可能理解有偏差,真正的理解估计得在项目中或看一些开源框架才能领会其意吧。
此篇初探:静态工厂模式
先上代码体会一下:
假设我们现在要造玩具狗。
一个Dog接口
package cn.liu.singlenessfactory;
/**
* 简单工厂
* @author Administrator
*
*/
public interface Dog {
void colour();
}
两种颜色的狗,要按设计模板去实现。
两个实现类:
package cn.liu.singlenessfactory;
public class WhiteDog implements Dog{
@Override
public void colour() {
System.out.println("我是白色的小狗");
}
}
package cn.liu.singlenessfactory;
public class YellowDog implements Dog{
@Override
public void colour() {
System.out.println("我是黄色的小狗");
}
}
现在工厂集集成去生成玩具狗
提供new对象方法的专门类
package cn.liu.singlenessfactory;
/**
* 提供实现其他方法实例化的类
* @author Administrator
*
*/
public class Factory {
public static Dog factory(String type) {
if(type.equals("WhiteDog")) {
return new WhiteDog();
}else if(type.equals("YellowDog")) {
return new YellowDog();
}else {
return null;
}
}
}
或可以写为:
package cn.liu.singlenessfactory;
/**
* 提供生成对象的类
* @author Administrator
*
*/
public class Factory2 {
public static Dog createWDog() {
return new WhiteDog();
}
public static Dog createYDog() {
return new YellowDog();
}
}
现在来一个调用者去调用。
package cn.liu.singlenessfactory;
public class Demo01 {
public static void main(String[] args) {
//通过一个接口实现new功能
Dog m1 = new Factory().factory("WhiteDog");
Dog m2 = new Factory().factory("YellowDog");
m1.colour();
m2.colour();
}
}
或是:
package cn.liu.singlenessfactory;
public class Demo02 {
public static void main(String[] args) {
Dog s1 = new Factory2().createWDog();
Dog s2 = new Factory2().createYDog();
s1.colour();
s2.colour();
}
}
结果:
现在画图来梳理一下思路。(不是标准的UML,只要能说明从属关系就行)箭头就是,此类实现依赖箭头所指的接口或类