一. 工厂方法的成员
1. 抽象工厂类:提供具体工厂的类或者接口
2. 具体工厂类:抽象工厂类的具体实现
3. 抽象产品类:提供具体产品的类或者接口
4. 具体产品类:抽象产品类的具体实现
二. 例子(网上找的,感觉很好的例子)
// 抽象工厂方法
public
interface AbstractFactory {
public Plant createPlant();
public Fruit createFruit() ;
}
//具体工厂方法
public
class FactoryA
implements AbstractFactory {
public Plant createPlant() {
return
new PlantA();
}
public Fruit createFruit() {
return
new FruitA();
}
}
public
class FactoryB
implements AbstractFactory {
public Plant createPlant() {
return
new PlantB();
}
public Fruit createFruit() {
return
new FruitB();
}
}
// 产品 Plant接口
public
interface Plant { }
//具体产品PlantA,PlantB
public
class PlantA
implements Plant {
public PlantA () {
System.out.println("create PlantA !");
}
public
void doSomething() {
System.out.println(" PlantA do something ...");
}
}
public
class PlantB
implements Plant {
public PlantB () {
System.out.println("create PlantB !");
}
public
void doSomething() {
System.out.println(" PlantB do something ...");
}
}
// 产品 Fruit接口
public
interface Fruit { }
//具体产品FruitA,FruitB
public
class FruitA
implements Fruit {
public FruitA() {
System.out.println("create FruitA !");
}
public
void doSomething() {
System.out.println(" FruitA do something ...");
}
}
public
class FruitB
implements Fruit {
public FruitB() {
System.out.println("create FruitB !");
}
public
void doSomething() {
System.out.println(" FruitB do something ...");
}
}