设计模式之工厂方法模式
实体类:
/**
* 包装接口
*/
public interface Bag {
void pack();
}
import com.enjoy.entity.Bag;
/**
* 苹果包装
* Created by Peter on 10/9 009.
*/
public class AppleBag implements Bag {
@Override
public void pack() {
System.out.print("--苹果使用纸箱包装");
}
}
import com.enjoy.entity.Bag;
/**
* 香蕉包装
*/
public class BananaBag implements Bag {
@Override
public void pack() {
System.out.print("--香蕉使用竹萝包装");
}
}
import com.enjoy.entity.Bag;
/**
* 包装工厂方法接口
*/
public interface BagFactory {
Bag getBag();// 打包指令
}
import com.enjoy.entity.Bag;
import com.enjoy.entity.bag.AppleBag;
/**
* 苹果-包装工厂方法
*/
public class AppleBagFactory implements BagFactory {
public Bag getBag(){
return new AppleBag();
}
}
import com.enjoy.entity.Bag;
import com.enjoy.entity.bag.BananaBag;
/**
* 香蕉-包装工厂方法模式
*/
public class BananaBagFactory implements com.enjoy.create.fatory.fatoryMethod.BagFactory {
public Bag getBag() {
return new BananaBag();
}
}
import com.enjoy.entity.Fruit;
/**
* 水果工厂方法接口
*/
public interface FruitFactory {
public Fruit getFruit(); // 摘水果指令
}
import com.enjoy.entity.fruit.Apple;
import com.enjoy.entity.Fruit;
/**
* 苹果-工厂方法
*/
public class AppleFactory implements FruitFactory {
@Override
public Fruit getFruit() {
return new Apple();
}
}
import com.enjoy.entity.fruit.Banana;
import com.enjoy.entity.Fruit;
/**
* 香蕉-工厂方法
*/
public class BananaFactory implements FruitFactory {
@Override
public Fruit getFruit() {
return new Banana();
}
}
客户端
import com.enjoy.entity.Fruit;
import org.springframework.beans.factory.annotation.Autowired;
/**
* 工厂方法模式测试
*/
public class FactoryClient {
@Autowired
private static FruitFactory fruitFactory;
public static void main(String[] args) {
// 初始化苹果工厂
fruitFactory = new AppleFactory(); // spring配置
peterdo();
jamesdo();
}
//Peter自己吃苹果
public static void peterdo() {
Fruit fruit = fruitFactory.getFruit();
fruit.draw();
//。。。直接啃着吃,吃掉了
System.out.println("-----------------");
}
//送给james,切开吃苹果
public static void jamesdo() {
Fruit fruit = fruitFactory.getFruit();
fruit.draw();
//。。。切开吃
System.out.println("-----------------");
}
}