[关键字]:java,design pattern,设计模式,《Java与模式》,Factory
[环境]:StarUML5.0 + JDK6
[作者]:Winty ([email protected])
UML图:
代码:
/**
*工厂模式测试类
*@version 2009-4-3
*@author Winty(
[email protected])
*/
package pattern.factory;
public class Factory{
public static void main(String[] args){
Fruit fruit;
FruitGardener fruitGardener;
fruitGardener = new AppleGardener();
fruit = fruitGardener.factory();
fruit.plant();
fruit.harvest();
fruitGardener = new StrawberryGardener();
fruit = fruitGardener.factory();
fruit.plant();
fruit.harvest();
fruitGardener = new GrapeGardener();
fruit = fruitGardener.factory();
fruit.plant();
fruit.harvest();
}
}
/**
*抽象产品
*/
abstract class Fruit{
protected String name;
public abstract void plant();
public abstract void harvest();
}
/**
*具体产品(Apple)
*/
class Apple extends Fruit{
public Apple(){
name = "Apple";
}
@Override
public void plant(){
System.out.println(name + " plant");
}
@Override
public void harvest(){
System.out.println(name + " harvest");
}
}
/**
*具体产品(草莓)
*/
class Strawberry extends Fruit{
public Strawberry(){
name = "Strawberry";
}
@Override
public void plant(){
System.out.println(name + " plant");
}
@Override
public void harvest(){
System.out.println(name + " harvest");
}
}
/**
*具体产品(葡萄)
*/
class Grape extends Fruit{
public Grape(){
name = "Grape";
}
@Override
public void plant(){
System.out.println(name + " plant");
}
@Override
public void harvest(){
System.out.println(name + " harvest");
}
}
/**
*抽象工厂类
*/
abstract class FruitGardener{
public abstract Fruit factory();
}
/**
*具体Apple工厂
*/
class AppleGardener extends FruitGardener{
@Override
public Fruit factory(){
return new Apple();
}
}
/**
*具体草莓工厂
*/
class StrawberryGardener extends FruitGardener{
@Override
public Fruit factory(){
return new Strawberry();
}
}
/**
*具体葡萄工厂
*/
class GrapeGardener extends FruitGardener{
@Override
public Fruit factory(){
return new Grape();
}
}