一、前言:
地址:https://gitee.com/luoyanyong/PatternDemo
二、代码实现:
1、调用实现
//简单工厂模式
Fruit fruit = StaticFactory.getFruit(StaticFactory.TYPE_APPLE);
fruit.draw();
//多工厂模式调用
// Fruit fruitOrange = StaticFactory.getFruitOrange();
// fruitOrange.draw();
2、StaticFactory实现
/**
* 简单工厂模式 --- 静态工厂模式
*/
public class StaticFactory {
public static final int TYPE_APPLE = 1;//苹果
public static final int TYPE_ORANGE = 2;//橘子
public static final int TYPE_BANANA = 3;//香蕉
public static Fruit getFruit(int type){
if (TYPE_APPLE == type){
return new Apple();
}else if (TYPE_ORANGE == type){
return new Orange("Peter",80);
}else if (TYPE_BANANA == type){
return new Banana();
}
return null;
}
/**
* 多方法工厂
* @return
*/
public static Fruit getFruitApple(){
return new Apple();
}
public static Fruit getFruitOrange(){
return new Orange("Peter",80);
}
public static Fruit getFruitBanana(){
return new Banana();
}
}
3、其它类和接口
1、水果父类接口
/**
* 水果接口
*/
public interface Fruit {
int price();
void draw();
int accept(Visit visit);
}
2、苹果实现类
public class Apple implements Fruit {
private int price = 100;
public Apple() {
}
public Apple(int price) {
this.price = price;
}
@Override
public int price() {
return price;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public void draw() {
Log.d("LUO","苹果红富士");
}
@Override
public int accept(Visit visit) {
return visit.sell(this);//指针可以传递真实类型
}
}
3、橘子实现类
public class Orange implements Fruit {
private String name = "";
private int price = 70;
public Orange(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public int price() {
return price;
}
@Override
public void draw() {
Log.d("LUO", "砂糖橘");
}
@Override
public int accept(Visit visit) {
return visit.sell(this);
}
}
4、香蕉实现类
public class Banana implements Fruit {
private int price = 60;
public Banana() {
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public int price() {
return price;
}
@Override
public void draw() {
Log.d("LUO","仙人蕉");
}
@Override
public int accept(Visit visit) {
return visit.sell(this);
}
}