1.简单工厂模式
在不考虑扩展的情况下还是很好用的,其实我们写代码也很经常用到,其主要理解在于传入不同参数则构建不同对象,只有一个工厂,如需添加产品涉及到扩展需要修改比较多的东西,不符合开闭原则,如下例子所示,传入A则获得ABook,传入B则获得BBook:
package main.java.com.learn.factory.factory; public interface Book { void getKnowledge();
}
package main.java.com.learn.factory.factory; public class ABook implements Book{ @Override
public void getKnowledge() {
System.out.println("获得A知识");
}
}
package main.java.com.learn.factory.factory; public class BBook implements Book{
@Override
public void getKnowledge() {
System.out.println("获得B知识");
}
}
package main.java.com.learn.factory.factory; public class SimpleBookFactory { public static Book create(String type) {
if ("A" == type)
return new ABook();
else
return new BBook();
}
}
package main.java.com.learn.factory.factory; /**
* Created by garfield on 2016/6/13.
*/
public class SimpleBookFactoryTest { public static void main(String[] args){
Book a = SimpleBookFactory.create("A");
Book b = SimpleBookFactory.create("B");
a.getKnowledge();
b.getKnowledge();
}
}
输出结果:
获得A知识
获得B知识
2.工厂模式
工厂模式其实就是在简单工厂的基础上将创建对象的逻辑挪到客户端,如此一来便于扩展类的种类,但是麻烦了客户端的编辑,下面例子其实就是在原有Book类的基础上将逻辑封装成工厂:
三个基础Book类不变;
package main.java.com.learn.factory.factory.abstractFactory; /**
* Created by garfield on 2016/6/13.
*/
public abstract class Creator {
abstract Book create();
}
package main.java.com.learn.factory.factory.abstractFactory; /**
* Created by garfield on 2016/6/13.
*/
public class ACreatorFactory extends Creator {
@Override
Book create() {
return new ABook();
}
}
package main.java.com.learn.factory.factory.abstractFactory; /**
* Created by garfield on 2016/6/13.
*/
public class BCreatorFactory extends Creator {
@Override
Book create() {
return new BBook();
}
}
package main.java.com.learn.factory.factory.abstractFactory; /**
* Created by garfield on 2016/6/13.
*/
public class FactoryTest { public static void main(String[] args){
Creator creator = new ACreatorFactory();
Creator creator2 = new BCreatorFactory();
Book a = creator.create();
Book b = creator2.create();
a.getKnowledge();
b.getKnowledge(); }
}
输出结果:
获得A知识
获得B知识
3.抽象工厂模式
虽然工厂模式使得逻辑更加清晰,扩展变得独立,但是如果需要增加类的种类,需要增加的工厂数量也同步增长,这也为扩展带来了不小负担,这也是抽象工厂与之的差别;
三个基础类依然不变,但是工厂不再是单一产品的工厂,工厂可以创建产品簇:
package main.java.com.learn.factory.factory.abstractFactory; /**
* Created by garfield on 2016/6/13.
*/
public abstract class Creator {
abstract ABook createA();
abstract BBook createB(); }
package main.java.com.learn.factory.factory.abstractFactory; /**
* Created by garfield on 2016/6/13.
*/
public class Factory extends Creator {
@Override
ABook createA() {
return new ABook();
} @Override
BBook createB() {
return new BBook();
}
}
package main.java.com.learn.factory.factory.abstractFactory; /**
* Created by garfield on 2016/6/13.
*/
public class AbstractFactoryTest {
public static void main(String[] args){
Creator creator = new Factory();
ABook a = creator.createA();
BBook b = creator.createB();
a.getKnowledge();
b.getKnowledge();
}
}
测试结果:
获得A知识
获得B知识