工厂设计模式
简单工厂模式
基本介绍
- 简单工厂模式属于创建型模式,是工厂模式的一种,简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例。简单工厂模式是工厂模式家族中最简单实用的模式。
- 简单工厂模式:定义了一个创建对象的类,由这个类来封装实例化对象的行为(代码)
- 在软件开发中,当我们会用到大量的创建某种、某类或者某批对象时,就会使用到工厂模式。
简单工厂模式类图实例
简单工厂模式java实现代码
//Pizza抽象类
public abstract class Pizza {
protected String name;
public abstract void prepare();
public void bake(){
System.out.println(name+"baking");
}
public void cut(){
System.out.println(name+"cutting");
}
public void box(){
System.out.println(name+"boxing");
}
public void setName(String name) {
this.name = name;
}
//PepperPizza类继承了Pizza抽象类(泛化关系)
public class PepperPizza extends Pizza {
@Override
public void prepare() {
System.out.println("给胡椒披萨 准备原材料");
}
}
//GreekPizza类继承了Pizza抽象类(泛化关系)
public class GreekPizza extends Pizza {
@Override
public void prepare() {
System.out.println("给希腊披萨 准备原材料");
}
}
//CheesePizza 类继承了Pizza抽象类(泛化关系)
public class CheesePizza extends Pizza {
@Override
public void prepare() {
System.out.println("给制作奶酪披萨 准备原材料");
}
}
创建SimpleFactory类,分为普通工厂模式和静态工厂模式
public class SimpleFactory {
public Pizza createPizza(String orderType) {
Pizza pizza=null;
System.out.println("使用简单工厂模式");
if (orderType.equals("greek")){
pizza=new GreekPizza();
pizza.setName("希腊披萨");
}else if (orderType.equals("cheese")){
pizza=new CheesePizza();
pizza.setName("奶酪披萨");
}else if (orderType.equals("pepper")){
pizza=new PepperPizza();
pizza.setName("胡椒披萨");
}
return pizza;
}
public static Pizza createPizza2(String orderType) {
Pizza pizza=null;
System.out.println("使用简单工厂模式");
if (orderType.equals("greek")){
pizza=new GreekPizza();
pizza.setName("希腊披萨");
}else if (orderType.equals("cheese")){
pizza=new CheesePizza();
pizza.setName("奶酪披萨");
}else if (orderType.equals("pepper")){
pizza=new PepperPizza();
pizza.setName("胡椒披萨");
}
return pizza;
}
}
订购披萨:OrderPizza类——>普通工厂模式所对应的实现
public class OrderPizza {
SimpleFactory simpleFactory;
Pizza pizza = null;
public OrderPizza(SimpleFactory simpleFactory) {
setFactory(simpleFactory);
}
public void setFactory(SimpleFactory simpleFactory) {
String orderType = "";
this.simpleFactory = simpleFactory;
do {
orderType = getType();
pizza = this.simpleFactory.createPizza(orderType);
if (pizza!=null){
pizza.prepare();
pizza.bake();
pizza.cut();
pizza.box();
}else {
System.out.println("订购披萨失败");
break;
}
} while (true);
}
private String getType() {
try {
BufferedReader strin = new BufferedReader(new InputStreamReader(System.in));
System.out.println("input pizza 种类");
String str = strin.readLine();
return str;
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
}
订购披萨:OrderPizza2类——>静态工厂模式所对应的实现
public class OrderPizza2 {
Pizza pizza = null;
String orderType="";
public OrderPizza2() {
do {
orderType = getType();
pizza = SimpleFactory.createPizza2(orderType);
if (pizza!=null){
pizza.prepare();
pizza.bake();
pizza.cut();
pizza.box();
}else {
System.out.println("订购披萨失败");
break;
}
} while (true);
}
private String getType() {
try {
BufferedReader strin = new BufferedReader(new InputStreamReader(System.in));
System.out.println("input pizza 种类");
String str = strin.readLine();
return str;
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
}
披萨店:PizzaStore
public class PizzaStore {
public static void main(String[] args) {
//使用简单工厂
new OrderPizza2();
}
}
工厂方法模式
基本介绍
- 工厂方法模式设计方案:将披萨项目的实例化功能抽象成抽象方法,在不同的口味点餐子类中具体实现。
- 工厂方法模式:定义了一个创建对象的抽象方法,由子类决定要实例化的类。工厂方法模式将
对象的实例化推迟到子类。
工厂方法模式类图实例
工厂方法模式java实现代码
Pizza的抽象类:
public abstract class Pizza {
protected String name;
public abstract void prepare();
public void bake(){
System.out.println(name+"baking");
}
public void cut(){
System.out.println(name+"cutting");
}
public void box(){
System.out.println(name+"boxing");
}
public void setName(String name) {
this.name = name;
}
}
LDPepperPizza类继承Pizza抽象类:
public class LDPepperPizza extends Pizza {
@Override
public void prepare() {
setName("伦敦的胡椒Pizza");
System.out.println("伦敦的胡椒Pizza 准备原材料");
}
}
LDCheesePizza类继承Pizza抽象类:
public class LDCheesePizza extends Pizza{
@Override
public void prepare() {
setName("伦敦的奶酪Pizza");
System.out.println("伦敦的奶酪Pizza 准备原材料");
}
}
BJPepperPizza类继承Pizza抽象类:
public class BJPepperPizza extends Pizza {
@Override
public void prepare() {
setName("北京的胡椒Pizza");
System.out.println("北京的胡椒Pizza 准备原材料");
}
}
BJCheesePizza类继承Pizza抽象类:
public class BJCheesePizza extends Pizza {
@Override
public void prepare() {
setName("北京的奶酪Pizza");
System.out.println("北京的奶酪Pizza 准备原材料");
}
}
OrderPizza抽象类作为工厂方法模型的“工厂类”
public abstract class OrderPizza {
abstract Pizza createPizza(String orderType);
public OrderPizza() {
Pizza pizza = null;
String orderType;
do {
orderType = getType();
pizza = createPizza(orderType);
pizza.prepare();
pizza.cut();
pizza.bake();
pizza.box();
} while (true);
}
private String getType() {
try {
BufferedReader strin = new BufferedReader(new InputStreamReader(System.in));
System.out.println("input pizza 种类");
String str = strin.readLine();
return str;
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
}
LDOrderPizza类继承OrderPizza抽象类:
public class LDOrderPizza extends OrderPizza {
@Override
Pizza createPizza(String orderType) {
Pizza pizza=null;
if (orderType.equals("cheese")){
pizza = new LDCheesePizza();
}else if (orderType.equals("pepper")){
pizza = new LDPepperPizza();
}
return pizza;
}
}
BJOrderPizza类继承OrderPizza抽象类:
public class BJOrderPizza extends OrderPizza {
@Override
Pizza createPizza(String orderType) {
Pizza pizza = null;
if (orderType.equals("cheese")) {
pizza = new BJCheesePizza();
} else if (orderType.equals("pepper")) {
pizza = new BJPepperPizza();
}
return pizza;
}
}
PizzaStore类:程序入口
public class PizzaStore {
public static void main(String[] args) {
//创建北京口味的各种披萨
new BJOrderPizza();
}
}
抽象工厂模型
基本介绍
- 抽象工厂模型:定义了一个interface用于创建相关或有依赖关系的对象簇,而无需指明具体的类。
- 抽象工厂模式可以将简单工厂模式和工厂方法模式进行整合。
- 从设计层面来看,抽象工厂模式就是对简单工厂模式的改进(或者称为进一步的抽象)。
- 将工厂抽象成两层,AbstractFactory(抽象工厂)和具体实现的工厂子类。程序员可以根据创建对象类型使用对应的工厂子类。这样将单个的简单工厂类变成了工厂簇,更利于代码的维护和扩展。
- 类图
抽象工厂模式类图实例
抽象工厂模式java实现代码
Pizza的抽象类:
public abstract class Pizza {
protected String name;
public abstract void prepare();
public void bake(){
System.out.println(name+"baking");
}
public void cut(){
System.out.println(name+"cutting");
}
public void box(){
System.out.println(name+"boxing");
}
public void setName(String name) {
this.name = name;
}
}
LDPepperPizza类继承Pizza抽象类:
public class LDPepperPizza extends Pizza {
@Override
public void prepare() {
setName("伦敦的胡椒Pizza");
System.out.println("伦敦的胡椒Pizza 准备原材料");
}
}
LDCheesePizza类继承Pizza抽象类:
public class LDCheesePizza extends Pizza{
@Override
public void prepare() {
setName("伦敦的奶酪Pizza");
System.out.println("伦敦的奶酪Pizza 准备原材料");
}
}
BJPepperPizza类继承Pizza抽象类:
public class BJPepperPizza extends Pizza {
@Override
public void prepare() {
setName("北京的胡椒Pizza");
System.out.println("北京的胡椒Pizza 准备原材料");
}
}
BJCheesePizza类继承Pizza抽象类:
public class BJCheesePizza extends Pizza {
@Override
public void prepare() {
setName("北京的奶酪Pizza");
System.out.println("北京的奶酪Pizza 准备原材料");
}
}
一个抽象工厂模式的抽象层(接口)
public interface AbsFactory {
public Pizza createPizza(String orderType);
}
BJFactory 作为子工厂
public class BJFactory implements AbsFactory {
@Override
public Pizza createPizza(String orderType) {
System.out.println("使用的是抽象工厂模式");
Pizza pizza=null;
if (orderType.equals("cheese")){
pizza=new BJCheesePizza();
}else if (orderType.equals("pepper")){
pizza=new BJPepperPizza();
}
return pizza;
}
}
LDFactory 作为子工厂
public class LDFactory implements AbsFactory {
@Override
public Pizza createPizza(String orderType) {
System.out.println("使用的是抽象工厂模式");
Pizza pizza=null;
if (orderType.equals("cheese")){
pizza=new LDCheesePizza();
}else if (orderType.equals("peeper")){
pizza=new LDPepperPizza();
}
return pizza;
}
}
OrderPizza 订单pizza
public class OrderPizza {
AbsFactory absFactory = null;
public OrderPizza(AbsFactory factory){
setFactory(factory);
}
private void setFactory(AbsFactory factory) {
Pizza pizza = null;
String orderType = "";
this.absFactory = factory;
do {
orderType = getType();
pizza = factory.createPizza(orderType);
if (pizza != null) {
pizza.prepare();
pizza.bake();
pizza.cut();
pizza.box();
} else {
System.out.println("订购失败");
break;
}
} while (true);
}
private String getType() {
try {
BufferedReader strin = new BufferedReader(new InputStreamReader(System.in));
System.out.println("input pizza 种类");
String str = strin.readLine();
return str;
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
}
PizzaStore 类启动工厂
public class PizzaStore {
public static void main(String[] args) {
new OrderPizza(new BJFactory());
}
}
JDK源码分析
工厂模式在JDK-Calendar应用的源码分析
- 工厂模式在JDK-Calendar类中,就使用了简单工厂模式
- 源码分析
JDK-Calendar:java实现代码
自定义 Demo: Factory 类
public class Factory {
public static void main(String[] args) {
//getInstance是Calendar的静态方法
Calendar calendar = Calendar.getInstance();
System.out.println("年:" + calendar.get(Calendar.YEAR));
System.out.println("月:" + (calendar.get(Calendar.MONTH)+1));
System.out.println("日:" + calendar.get(Calendar.DAY_OF_MONTH));
System.out.println("时:" + calendar.get(Calendar.HOUR_OF_DAY));
System.out.println("分:" + calendar.get(Calendar.MINUTE));
System.out.println("秒:" + calendar.get(Calendar.SECOND));
}
}
追踪Calendar类的getInstance()静态方法
/**
* Gets a calendar using the default time zone and locale. The
* <code>Calendar</code> returned is based on the current time
* in the default time zone with the default
* {@link Locale.Category#FORMAT FORMAT} locale.
*
* @return a Calendar.
*/
public static Calendar getInstance()
{
return createCalendar(TimeZone.getDefault(), Locale.getDefault(Locale.Category.FORMAT));
}
追踪createCalendar方法:switch语句中根据传入不同的值返回不同类型的Calendar对象实例。
/**
* Gets a calendar with the specified time zone and locale.
* The <code>Calendar</code> returned is based on the current time
* in the given time zone with the given locale.
*
* @param zone the time zone to use
* @param aLocale the locale for the week data
* @return a Calendar.
*/
public static Calendar getInstance(TimeZone zone,
Locale aLocale)
{
return createCalendar(zone, aLocale);
}
private static Calendar createCalendar(TimeZone zone,
Locale aLocale)
{
CalendarProvider provider =
LocaleProviderAdapter.getAdapter(CalendarProvider.class, aLocale)
.getCalendarProvider();
if (provider != null) {
try {
return provider.getInstance(zone, aLocale);
} catch (IllegalArgumentException iae) {
// fall back to the default instantiation
}
}
Calendar cal = null;
if (aLocale.hasExtensions()) {
String caltype = aLocale.getUnicodeLocaleType("ca");
if (caltype != null) {
switch (caltype) {
case "buddhist":
cal = new BuddhistCalendar(zone, aLocale);
break;
case "japanese":
cal = new JapaneseImperialCalendar(zone, aLocale);
break;
case "gregory":
cal = new GregorianCalendar(zone, aLocale);
break;
}
}
}
if (cal == null) {
// If no known calendar type is explicitly specified,
// perform the traditional way to create a Calendar:
// create a BuddhistCalendar for th_TH locale,
// a JapaneseImperialCalendar for ja_JP_JP locale, or
// a GregorianCalendar for any other locales.
// NOTE: The language, country and variant strings are interned.
if (aLocale.getLanguage() == "th" && aLocale.getCountry() == "TH") {
cal = new BuddhistCalendar(zone, aLocale);
} else if (aLocale.getVariant() == "JP" && aLocale.getLanguage() == "ja"
&& aLocale.getCountry() == "JP") {
cal = new JapaneseImperialCalendar(zone, aLocale);
} else {
cal = new GregorianCalendar(zone, aLocale);
}
}
return cal;
}
工厂模式小结
- 工厂模式的意义
将实例化对象的代码提取出来,放到一个类中统一管理和维护,达到和主项目的依赖关系的解耦,从而提高项目的扩展和维护性。 - 三种工厂模式
- 设计模式的依赖抽象原则
- 创建对象实例时,不要直接new类,而是把这个new类的动作放在一个工厂的方法中,并返回,有的书上说,变量不要直接持有具体类的引用。
- 不要让类继承具体类,而是继承抽象类或者是实现interface(接口)
- 不要覆盖基类中已经实现的方法。