软件设计 2017-05-23
抽象工厂模式是工厂方法模式的进一步抽象。如果产品簇中只有一种产品,则退化为工厂方法模式。
* 苹果和土豆是园丁1的杰作
* 葡萄和西红柿是园丁2的杰作
public interface Fruit {
/*
* 生长
* 收获
* 栽种
*/
public void grow();
public void harvest();
public void plant();
}public class Apple implements Fruit {
private int treeAge;
public void grow() {
System.out.println("苹果正在生长,,,");
}
public void harvest() {
System.out.println("收获苹果");
}
public void plant() {
System.out.println("栽种苹果");
}
public int getTreeAge() {
return treeAge;
}
public void setTreeAge(int treeAge) {
this.treeAge = treeAge;
}
} public class Grape implements Fruit {
private boolean seedless;
public void grow() {
System.out.println("葡萄正在生长。。。");
}
public void harvest() {
System.out.println("收获葡萄。");
}
public void plant() {
System.out.println("栽种葡萄。");
}
public boolean isSeedless() {
return seedless;
}
public void setSeedless(boolean seedless) {
this.seedless = seedless;
}
} public interface Vegetable {
/*
* 生长
* 收获
* 栽种
*/
public void grow();
public void harvest();
public void plant();
} public class Potato implements Vegetable {
public void grow() {
System.out.println("土豆正在生长,,,");
}
public void harvest() {
System.out.println("收获土豆");
}
public void plant() {
System.out.println("栽种土豆");
}
} public class Tomato implements Vegetable {
public void grow() {
System.out.println("西红柿正在生长,,,");
}
public void harvest() {
System.out.println("收获西红柿");
}
public void plant() {
System.out.println("栽种西红柿");
}
} public interface Gardener {
/*
* 水果园丁
* 蔬菜园丁
* 水果蔬菜各两种
* 建立水果工厂的方法
*/
public Fruit factoryFruit();
public Vegetable factoryVegetable();
} public class ConcreteGardener11 implements Gardener {
//等级为1的园丁生产的水果和蔬菜
/*
* 苹果和土豆是园丁1的杰作,或者说是一等产品
* 葡萄和西红柿是园丁2的杰作,或者说是二等产品
*/
public Fruit factoryFruit() {
return new Apple();
}
public Vegetable factoryVegetable() {
return new Potato();
}
} public class ConcreteGardener12 implements Gardener {
//等级为2的园丁生产的水果和蔬菜
/*
* 苹果和土豆是园丁1的杰作,或者说是一等产品
* 葡萄和西红柿是园丁2的杰作,或者说是二等产品
*/
public Fruit factoryFruit() {
return new Grape();
}
public Vegetable factoryVegetable() {
return new Tomato();
}
} public class ClientDemo {
public static void main(String[] args) {
/*
* 苹果和土豆是园丁1的杰作,或者说是一等产品
* 葡萄和西红柿是园丁2的杰作,或者说是二等产品
*/
Gardener gardener1=new ConcreteGardener11();
Gardener gardener2=new ConcreteGardener12();
Fruit apple = gardener1.factoryFruit();
Vegetable potato=gardener1.factoryVegetable();
Fruit grape = gardener2.factoryFruit();
Vegetable tomato=gardener2.factoryVegetable();
apple.plant();
apple.grow();
apple.harvest();
potato.plant();
potato.grow();
potato.harvest();
grape.plant();
grape.grow();
grape.harvest();
tomato.plant();
tomato.grow();
tomato.harvest();
}
} 栽种苹果
苹果正在生长,,,
收获苹果
栽种土豆
土豆正在生长,,,
收获土豆
栽种葡萄。
葡萄正在生长。。。
收获葡萄。
栽种西红柿
西红柿正在生长,,,
收获西红柿