[关键字]:java,design pattern,设计模式,《Java与模式》,Factory
[环境]:StarUML5.0 + JDK6
[作者]:Winty (wintys@gmail.com)
UML图:
代码:
/**
*工厂模式测试类
*@version 2009-4-3
*@author Winty(wintys@gmail.com)
*/
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();
}
}
posted on 2009-04-14 12:32
天堂露珠 阅读(1110)
评论(0) 编辑 收藏 所属分类:
Pattern