抽象工厂模式(Abstract Factory Pattern):提供一个创建一系列相关或相互依赖对象的接口,而无须指定它们具体的类。抽象工厂模式又称为Kit模式,它是一种对象创建型模式。举例子说明。
代码如下:
package abstractfactory;
public interface Fruit
{
public String getName();
}
package abstractfactory;
public interface Veggie
{
public String getName();
}
package abstractfactory;
public class NorthernFruit implements Fruit
{
private String name;
public NorthernFruit(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
package abstractfactory;
public class TropicalFruit implements Fruit
{
private String name;
public TropicalFruit(String name)
{
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
package abstractfactory;
public interface Gardener
{
public Fruit createFruit(String name);
public Veggie createVeggie(String name);
}
package abstractfactory;
public class TropicalGardener implements Gardener
{
public Fruit createFruit(String name)
{
return new TropicalFruit(name);
}
public Veggie createVeggie(String name)
{
return new TropicalVeggie(name);
}
}
package abstractfactory;
public class NorthernGardener implements Gardener
{
public Fruit createFruit(String name)
{
return new NorthernFruit(name);
}
public Veggie createVeggie(String name)
{
return new NorthernVeggie(name);
}
}
package abstractfactory;
public class TestClient {
private static Gardener gardener;
public static void main(String[] args){
gardener=new NorthernGardener();
Fruit f=gardener.createFruit("苹果");
System.out.println(f.getName());
Veggie v=gardener.createVeggie("香菜");
System.out.println(v.getName());
}
}