简单工厂模式
实现方式:
√使用Java接口或者Java抽象类;
√使用过个工厂方法;
√产品循环使用;
√多态的丧失和模式的退化,主要体现在工厂方法创建的对象、工厂方法返回的类型、工厂等级结构三个方面。
(1)Fruit.java(实现水果产品接口)
public interface Fruit{
void plant();
void grow();
void harvest();
}
(2)Apple.java(实现具体产品——苹果)
public class Apple implements Fruit{
private int treeAge;
public void plant(){
System.out.println("Apple has been planted.");
}
public void grow(){
System.out.println("Apple is growing...");
}
public void harvest(){
System.out.println("Apple has been harvest.");
}
public int getTreeAge(){
return treeAge;
}
public void setTreeAge(int treeAge){
this.treeAge = treeAge;
}
}
(3)Grape.java(实现具体产品——葡萄)
public class Grape implements Fruit{
private boolean seedless;
public void plant(){
System.out.println("Grape has been planted.");
}
public void grow(){
System.out.println("Grape is growing...");
}
public void harvest(){
System.out.println("Grape has been harvest.");
}
public boolean getSeedless(){
return seedless;
}
public void setSeedless(int seedless){
this.seedless = seedless;
}
public static void log(String msg){
System.out.println(msg);
}
}
(4)Strawberry.java(实现具体产品——草莓)
public class Strawberry implements Fruit{
private boolean seedless;
public void plant(){
System.out.println("Strawberry has been planted.");
}
public void grow(){
System.out.println("Strawberry is growing...");
}
public void harvest(){
System.out.println("Strawberry has been harvest.");
}
public static void log(String msg){
System.out.println(msg);
}
}
(5)FruitGardener.java(实现水果工厂接口)
public interface FruitGardener{
public Fruit factory();
}
(6)AppleGardener
.java(实现苹果工厂)
public class AppleGardener implements FruitGardener{
public Fruit factory(){
Fruit f = new Apple();
System.out.println("水果工厂(AppleGardener)成功创建一个水果:苹果!");
return f;
}
}
(7)GrapeGardener.java(实现葡萄工厂)
public class GrapeGardener implements FruitGardener{
public Fruit factory(){
Fruit f = new Grape();
System.out.println("水果工厂(GrapeGardener)成功创建一个水果:葡萄!");
return f;
}
}
(8)StrawberryGardener.java(实现草莓工厂)
public class StrawberryGardener implements FruitGardener{
public Fruit factory(){
Fruit f = new Strawberry();
System.out.println("水果工厂(StrawberryGardener)成功创建一个水果:草莓!");
return f;
}
}
(9)TestApp.java(客户端测试类)
public class TestApp{
private FruitGardener f1, f2, f3;
private Fruit p1, p2, p3;
private void test(){
//实例化水果工厂
f1 = new AppleGardener();
f2 = new GrapeGardener();
f3 = new StrawberryGardener();
//从水果工厂生产水果
p1 = f1.factory();
p2 = f2.factory();
p3 = f3.factory();
}
public static void main(String[] args){
TestApp testapp = new TestApp();
testapp.test();
}
}