抽象工厂模式以一种倾斜的方式支持增加新的产品,它为新产品族的增加提供方便,而不能为新的产品等级结构的增加提供这样的方便。
如下是这个系统角色的相图:
系统的设计类图如下:
package kai.abstractfactory.farm;
public interface Gardener {}
生产北方的水果的蔬菜
工厂方法:使用了单例模式
package kai.factory.farm;
import kai.abstractclass.farm.Fruit;
import kai.abstractclass.farm.Veggie;
import kai.abstractfactory.farm.Gardener;
import kai.entity.farm.NorthernFruit;
import kai.entity.farm.NorthernVeggie;
public class NorthernGardener implements Gardener {
private static NorthernGardener nGardener=new NorthernGardener();
private NorthernGardener(){}
public static NorthernGardener getNorthernGardener(){
return nGardener;
}
/**
* 生产北方的水果
*/
public Fruit createFruit(String name) {
return new NorthernFruit(name);
}
/**
* 生产北方的蔬菜
*/
public Veggie createVeggie(String name) {
return new NorthernVeggie(name);
}
}
package kai.factory.farm;
import kai.abstractclass.farm.Fruit;
import kai.abstractclass.farm.Veggie;
import kai.abstractfactory.farm.Gardener;
import kai.entity.farm.TropicalFruit;
import kai.entity.farm.TropicalVeggie;
public class TropicalGardener implements Gardener {
private static TropicalGardener tGardener=new TropicalGardener();
private TropicalGardener() {
}
public static TropicalGardener getTropicalGardener(){
return tGardener;
}
/**
* 生产热带的水果
*/
public Fruit createFruit(String name){
return new TropicalFruit(name);
}
/**
* 生产热带的蔬菜
*/
public Veggie createVeggie(String name){
return new TropicalVeggie(name);
}
}
package kai.abstractclass.farm;
public interface Fruit {}
--------------------------------
package kai.abstractclass.farm;
public interface Veggie {}
package kai.entity.farm;
import kai.abstractclass.farm.Fruit;
public class NorthernFruit implements Fruit {
private String name;
public NorthernFruit(String name) {
System.out.println(name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package kai.entity.farm;
import kai.abstractclass.farm.Veggie;
public class NorthernVeggie implements Veggie {
private String name;
public NorthernVeggie(String name) {
System.out.println(name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package kai.entity.farm;
import kai.abstractclass.farm.Fruit;
public class TropicalFruit implements Fruit {
private String name;
public TropicalFruit(String name) {
System.out.println(name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package kai.entity.farm;
import kai.abstractclass.farm.Veggie;
public class TropicalVeggie implements Veggie {
private String name;
public TropicalVeggie(String name) {
System.out.println(name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}