(一)简单工厂。它的缺点很明显,当需要再添加一个WhiteHuman类时,需要在工厂类中修改,则代码的耦合性很高。
//创建需要用工厂new的class
public interface Human {
}
public class BlackHuman implements Human {
public BlackHuman() {
System.out.println("BlackHuman.BlackHuman()");
}
}
public class YellowHuman implements Human{
public YellowHuman(){
System.out.println("YellowHuman.YellowHuman()");
}
}
//创建工厂
public class HumanFactory {
public Human create(Integer type) {
switch (type) {
case 1:
return new YellowHuman();
case 2:
return new BlackHuman();
default:
break;
}
return null;
}
}
//测试
public class SimplTest {
public static void main(String[] args) {
HumanFactory factory = new HumanFactory();
Human yellow = factory.create(1);
Human black = factory.create(2);
}
}
(二)工厂方法。所有的对象都是在同一个等级,即所有的对象的类都是实现同一个接口或者继承同一个类。然而,每个工厂只能生产一个类型的对象。那么,当需要同等级,不同类型的对象的时候,就需要创建不同的工厂类,来创建单一的对象。当需要再添加一个WhiteHuman的时候,只需要实现Human,并且新建一个工厂,实现HumanFactory,对以前的代码没任何修改,降低了代码之间的耦合度。
public interface HumanFactory {
public Human create();
}
public class BlackManFactory implements HumanFactory {
@Override
public Human create() {
return new BlackHuman();
}
}
public class YellowManFactory implements HumanFactory {
@Override
public Human create() {
return new YellowHuman();
}
}
public class MethodTest {
public static void main(String[] args) {
YelloManFactory yellowManFactory = new YellowManFactory();
BlackManFactory blackManFactory = new BlackManFactory();
Human yellow = yellowManFactory.create();
Human black = blackManFactory.create();
}
}
(三)抽象工厂。它主要是针对不同对象等级的工厂,当BlcakHuman,YellowHuman下还有男性和女性之分的时候,如果用工厂方法来创建,那么人类,工厂之间的逻辑关系就会比较混乱。仅仅创建一个女性的工厂,就需要一个黑种人,黄种人的工厂来创建,这样代码很臃肿,所以用抽象工厂方法来创建。一个抽象工厂可以可以创建多个对象。当需要添加一个WhiteHuman时,需要对所有的工厂类进行添加,代码间的耦合度增加了。所以在用抽象工厂之前,一定要确立需要创建的对象之间的关系,否则修改的时候会很麻烦。
//需要创建的对象之间的关系和类
public class BlackFemale extends BlackHuman{
public BlackFemale(){
System.out.println("BlackFemale.BlackFemale()");
}
}
public class BlackMale extends BlackHuman{
public BlackMale(){
System.out.println("BlackMale.BlackMale()");
}
}
public class YellowFemale extends YellowHuman {
public YellowFemale(){
System.out.println("YellowFemale.YellowFemale()");
}
}
public class YellowMale extends YellowHuman{
public YellowMale(){
System.out.println("YellowMale.YellowMale()");
}
}
//工厂
public interface HumanFactory {
public Human createYellow();
public Human createBlack();
}
public class FemaleFactory implements HumanFactory{
@Override
public Human createYellow() {
return new YellowFemale();
}
@Override
public Human createBlack() {
return new BlackFemale();
}
}
public class MaleFactory implements HumanFactory{
@Override
public Human createYellow() {
return new YellowManle();
}
@Override
public Human createBlack() {
return new BlackMale();
}
}
public class AbstractTest {
public static void main(String[] args) {
FemaleFactory femaleFactory = new FemaleFactory();
MaleFactory maleFactory = new MaleFactory();
femaleFactory.createBlack();
femaleFactory.createYellow();
maleFactory.createBlack();
}
}