作用:
工厂模式主要是为了将创建对象的过程交给工厂,降低代码侵入性,降低耦合度。
类型:创建型模式
工厂模式分为三类:
1、 普通工厂模式
2、 工厂方法模式
3、 静态工厂方法模式
关系图:
1、普通工厂模式:
创建People接口:
/**
* Create by zhaihongwei on 2018/3/9
*/
public interface People {
public void say();
}
创建实现类:
/**
* Create by zhaihongwei on 2018/3/9
*/
public class Chinese implements People{
@Override
public void say() {
System.out.println("你好!");
}
}
/**
* Create by zhaihongwei on 2018/3/9
*/
public class American implements People {
@Override
public void say() {
System.out.println("Hello!");
}
}
创建工厂类:
/**
* Create by zhaihongwei on 2018/3/9
*/
public class PeopleFactory {
public People everyOneSay(String everyOne) {
if("Chinese".equals(everyOne)) {
return new Chinese();
}else if ("American".equals(everyOne)) {
return new American();
}else {
System.out.println("没有这个国家的人");
return null;
}
}
}
创建测试类:
/**
* Create by zhaihongwei on 2018/3/9
*/
public class FactoryTest {
public static void main(String[] args) {
PeopleFactory factory = new PeopleFactory();
People chinese = factory.everyOneSay("Chinese");
chinese.say();
}
}
这种普通的工厂模式,基本上不使用,如果传递的字符创出错,则无法正确的创建对象。
2、工厂方法模式:
是对普通方法的改进,工厂方法模式提供多个工厂方法,分别创建对象实例。
创建工厂类:
/**
* Create by zhaihongwei on 2018/3/9
*/
public class PeopleFactory {
public People createChinese() {
return new Chinese();
}
public People createAmerican() {
return new American();
}
}
创建测试类:
/**
* Create by zhaihongwei on 2018/3/9
*/
public class FactoryTest {
public static void main(String[] args) {
PeopleFactory factory = new PeopleFactory();
People chinese = factory.createChinese();
chinese.say();
}
}
3、 静态工厂方法模式:
将多个工厂方法创建为静态方法,不需要创建实例,直接调用。
创建工厂类:
/**
* Create by zhaihongwei on 2018/3/9
*/
public class PeopleFactory {
public static People createChinese() {
return new Chinese();
}
public static People createAmerican() {
return new American();
}
}
创建测试类:
/**
* Create by zhaihongwei on 2018/3/9
*/
public class FactoryTest {
public static void main(String[] args) {
People chinese = PeopleFactory.createChinese();
chinese.say();
}
}
总结:
在以上的三种模式中,第一种如果传入的字符串有误,不能正确创建对象,第三种相对于第二种,不需要实例化工厂类,所以,大多数情况下,我们会选用第三种——静态工厂方法模式。
工厂方法的好处:
1 工厂方法封装了对象创建的细节,将对象创建代码和其他部分脱离,减少相干性.
2 有利于同类对象创建的统一管理和控制
3 你所关心的仅仅是工厂方法返回的接口方法,不必关心实现细节