参考:《设计模式那点事》
一、工厂方法模式
1-概述
一:工厂方法模式 (1)创建产品对象的工厂接口 (2)子类对象决定实例化的具体对象;工厂不负责具体的对象创建 二:设计原则 (1)"开-闭" (2)依赖倒置 无论工厂或者产品依赖于抽象而非具体的实现类 三:场合 (1)子类可能很多,以后要不断增加不同的子类实现
package SheJiMoShiNaDianShi.Factory.itf;
import SheJiMoShiNaDianShi.Factory.model.AbstractSword;
/**
* Created by hjw on 16/8/28.
* 抽象工厂-生产抽象宝刀
*/
public interface ISwordFactory {
public AbstractSword creatSword();
}
=================具体工厂1======================
package SheJiMoShiNaDianShi.Factory;
import SheJiMoShiNaDianShi.Factory.itf.ISwordFactory;
import SheJiMoShiNaDianShi.Factory.model.AbstractSword;
import SheJiMoShiNaDianShi.Factory.model.object.QiXingSword;
/**
* Created by hjw on 16/8/28.
* Caocao具体工厂-生产七星宝刀的工厂
*/
public class Caocao implements ISwordFactory {
@Override
public AbstractSword creatSword() {
return new QiXingSword();
}
}
===================具体工厂2====================
package SheJiMoShiNaDianShi.Factory;
import SheJiMoShiNaDianShi.Factory.itf.ISwordFactory;
import SheJiMoShiNaDianShi.Factory.model.AbstractSword;
import SheJiMoShiNaDianShi.Factory.model.object.BaXingSword;
/**
* Created by hjw on 16/8/28.
*/
public class Caocao2 implements ISwordFactory {
@Override
public AbstractSword creatSword() {
return new BaXingSword();
}
}
=================抽象产品======================
package SheJiMoShiNaDianShi.Factory.model;
/**
* Created by hjw on 16/8/28.
* 抽象的产品
*/
public abstract class AbstractSword {
//宝刀的名字
private String name;
public AbstractSword(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
==================具体产品1==========================
package SheJiMoShiNaDianShi.Factory.model.object;
import SheJiMoShiNaDianShi.Factory.model.AbstractSword;
/**
* Created by hjw on 16/8/28.
*/
public class BaXingSword extends AbstractSword {
public BaXingSword() {
super("八星宝刀");
}
}
==================具体产品2==========================
package SheJiMoShiNaDianShi.Factory.model.object;
import SheJiMoShiNaDianShi.Factory.model.AbstractSword;
/**
* Created by hjw on 16/8/28.
* 七星宝刀-具体的产品
*/
public class QiXingSword extends AbstractSword {
public QiXingSword() {
super("七星宝刀");
}
}
package SheJiMoShiNaDianShi.Factory;
import SheJiMoShiNaDianShi.Factory.itf.ISwordFactory;
import SheJiMoShiNaDianShi.Factory.model.AbstractSword;
/**
* Created by hjw on 16/8/28.
*/
public class MainApp {
public static void main(String[] args) {
ISwordFactory iSwordFactory = new Caocao();
AbstractSword abstractSword = iSwordFactory.creatSword();
System.out.println(abstractSword.getName());
iSwordFactory = new Caocao2();
abstractSword = iSwordFactory.creatSword();
System.out.println(abstractSword.getName());
}
}