在所有的开发模式中,平常用的最多的恐怕就是工程模式,我个人感觉,工厂模式实际上就是面向接口编程的一种实现方式,使用的时候没有必要去严格的区分其究竟是是简单工程模式还是抽象工厂模式还是工厂方法模式。
下面我用实例来描述一下工厂模式的三种方式:
1.简单工厂模式
简单工厂模式(simple factory)是类的创建模式,又叫静态工厂方法(staticfactory method)模式。
简单工厂模式就是由一个工厂类根据传入的参数决定创建哪一种的产品类。
有4个角色
工厂类角色:是具体产品类角色直接调用者。
抽象产品角色:接口或抽象类,负责具体产品角色的定义,及与客户端的交互。
具体产品角色:被工厂类创建的对象,也是客户端实际操作对象。
客户端:调用工厂类产生实例,并调用实例的方法进行相应工作。
public interface people{
public void show();
}
public class Boy implements people{
public void say(){
System.out.println("I'm a boy");
}
}
public class Girl implements people{
public void say(){
System.out.println("I'm a Girl");
}
}
public class peopleFactory{
public static people create(int type){
if(type==1){
return new Boy();
}else if(type==2){
return new Girl();
}
}
}
public class test{
public static void main(String []args){
people p=peopleFactory.create(1);
p.show();
}
}
简单明了,但简单工厂模式有个缺点就是不利于扩展,什么意思呢,就是如果有多个类都实现同一个借口那么Factory中就会出现很多的if语句,这显然是不行的。于是就有了工厂方法模式。
2. 工厂方法模式
工厂方法模式(Factory Method pattern)是最典型的模板方法模式(TempleteMethod pattern)应用。
如图:通过上面这张图看,就比较直观了
基于面向接口编程的原理,创建部分成为抽象工厂与实体工厂,创建出的对象成为抽象产品与实体产品。你可能知道为什么它能解决上面的问题了:多了一个新对象,只需添加一套对应的工厂和产品就可以了,不需要修改原代码,或只需进行少量的修改。
具体:
实体工厂实现抽象工厂,实体产品实现抽象产品;抽象工厂生产抽象产品,实体工厂生产实体产品;实体工厂A生产实体产品A,实体工厂B生产实体产品B。
public interface Icar{
public void docar();
}
public class Bwm implements Icar{
public void docar(){
System.out.println("I'm bmw");
}
}
public class Buick implements Icar{
public void docar(){
System.out.println("I'mbuick");
}
}
public interface Icarfactory{
public Icar createCar();
}
public class BmwFactory implements Icarfactory{
public Icar createCar(){
return new Bwm();
}
}
public class BuickFactory implements Icarfactory{
public Icar createCar(){
return new Buick();
}
}
public class test{
public static void main(String []args){
Icarfactory factory=new BmwFactory();
Icar bwm= factory.createCar();
bwm.docar();
factory=new BuickFactory();
Icar buick= factory.createCar();
buick.docar();
}
}
如果这时候再来一辆奔驰,只需要再加一套对应的工厂和和产品就可以了,不需要修改源代码。
3.抽象工厂模式
我对抽象工厂模式的理解就是,一个实例工厂可以生产多种类型的实例,那那这种工厂模式就是抽象工厂模式。
还是看例子:
interface IProduct1 {
public void show();
}
interface IProduct2 {
public void show();
}
class Product1 implements IProduct1 {
public void show() {
System.out.println("这是1型产品");
} }
class Product2 implements IProduct2 {
public void show() {
System.out.println("这是2型产品");
}
}
interface IFactory {
public IProduct1 createProduct1();
public IProduct2 createProduct2();
}
class Factory implements IFactory{
public IProduct1 createProduct1() {
return new Product1();
}
public IProduct2 createProduct2() {
return new Product2();
}
}
public class Client {
public static void main(String[] args){
IFactory factory = new Factory();
factory.createProduct1().show();
factory.createProduct2().show();
}
}