一、简单工厂模式说明:
1. 简单工厂模式主要涉及到工厂角色(工厂类)、具体产品角色(具体产品类)和抽象产品角色(产品接口)三种。
2. 工厂角色在简单工厂模式中占有核心的地位,该类由客户端直接调用形成产品。通常由具体的Java类构成。
3. 抽象产品角色,通常由接口或者抽象类完成。
4. 具体的产品角色从抽象产品角色继承,在工厂类中被实例化,而它的实现细节被隐藏。
5. 简单工厂模式的结构图如下所示:
二、简单工厂模式设计:
例如,设计一个果园管理系统,果园中包括有苹果、葡萄、梨三种水果。
1. 首先可以定义一个水果接口:
package com.solid.simplefactory;
/**
* 简单工厂模式(产品接口)
* @author solid
*
*/
public interface Fruit {
//种植
void grant();
//生长
void grow();
//收获
void harvest();
}
2. 具体的水果类(苹果、葡萄、梨):
package com.solid.simplefactory;
/**
* 简单工厂模式(具体产品一)
* @author solid
*
*/
public class Apple implements Fruit {
//苹果种植
public void grant() {
log("apple grant");
}
//苹果生长
public void grow() {
log("apple grow");
}
//苹果收获
public void harvest() {
log("apple harvest");
}
//公共方法
public static void log(String str) {
System.out.println(str);
}
}
package com.solid.simplefactory;
/**
* 简单工厂模式(具体产品二)
* @author solid
*
*/
public class Grape implements Fruit {
//葡萄种植
public void grant() {
log("grape grant");
}
//葡萄生长
public void grow() {
log("grape grow");
}
//葡萄收获
public void harvest() {
log("grape harvest");
}
//公共方法
public static void log(String str) {
System.out.println(str);
}
}
package com.solid.simplefactory;
/**
* 简单工厂模式(具体产品三)
* @author solid
*
*/
public class Pear implements Fruit {
//梨种植
public void grant() {
log("pear grant");
}
//梨生长
public void grow() {
log("pear grow");
}
//梨收获
public void harvest() {
log("pear harvest");
}
//公共方法
public static void log(String str) {
System.out.println(str);
}
}
3. 工厂类:
package com.solid.simplefactory;
/**
* 简单工厂模式(工厂类)
* @author solid
*
*/
public class FruitFactory {
public static Fruit factory(String fruit) throws BadFruitException {
if(fruit.equalsIgnoreCase("apple")) {
return new Apple();
} else if(fruit.equalsIgnoreCase("grape")) {
return new Grape();
} else if(fruit.equalsIgnoreCase("Pear")) {
return new Pear();
} else {
throw new BadFruitException("BadFruit request");
}
}
}
4. 异常类:
package com.solid.simplefactory;
/**
* 简单工厂模式(异常类)
* @author solid
*
*/
public class BadFruitException extends Exception {
public BadFruitException(String message) {
System.out.println("sorry, " + message);
}
}