Simple Factory模式(又称Static Factory模式)
一个Simple Factory生产成品,而对客户端隐藏产品产生的细节。实作时定义一个产品介面(interface),并透过特定静态方法来建立成品。
假设有一个水果工厂,购买水果的客人不用知道水果是如何制作的,他只要知道如何吃水果就可以了。
Java代码 收藏代码
/**
*
* @author Jerval
* @date 2011-4-11
*/
public interface IFruit {
public void eat();
}
/**
*
* @author Jerval
* @date 2011-4-11
*/
public class Apple implements IFruit{
public void eat() {
System.out.println("eat an apple");
}
}
/**
*
* @author Jerval
* @date 2011-4-11
*/
public class Banana implements IFruit{
public void eat() {
System.out.println("eat an banana");
}
}
/**
*
* @author Jerval
* @date 2011-4-11
*/
public class FruitFactory {
/**
* generate fruit factory
*
* @param clazz
* @return
*/
public static IFruit getFruit(String fruitName){
if("apple".equalsIgnoreCase(fruitName)){
return new Apple();
}else if("banana".equalsIgnoreCase(fruitName)){
return new Banana();
}else{
System.out.println("can not find the fruit named:"+fruitName);
}
return null;
}
}
/**
*
* @author Jerval
* @date 2011-4-11
*/
public class MainClass {
public static void main(String[] args) {
Apple apple = (Apple) FruitFactory.getFruit("apple");
Banana banana = (Banana) FruitFactory.getFruit("banana");
apple.eat();
banana.eat();
}
}
一个Simple Factory生产成品,而对客户端隐藏产品产生的细节。实作时定义一个产品介面(interface),并透过特定静态方法来建立成品。
假设有一个水果工厂,购买水果的客人不用知道水果是如何制作的,他只要知道如何吃水果就可以了。
Java代码 收藏代码
/**
*
* @author Jerval
* @date 2011-4-11
*/
public interface IFruit {
public void eat();
}
/**
*
* @author Jerval
* @date 2011-4-11
*/
public class Apple implements IFruit{
public void eat() {
System.out.println("eat an apple");
}
}
/**
*
* @author Jerval
* @date 2011-4-11
*/
public class Banana implements IFruit{
public void eat() {
System.out.println("eat an banana");
}
}
/**
*
* @author Jerval
* @date 2011-4-11
*/
public class FruitFactory {
/**
* generate fruit factory
*
* @param clazz
* @return
*/
public static IFruit getFruit(String fruitName){
if("apple".equalsIgnoreCase(fruitName)){
return new Apple();
}else if("banana".equalsIgnoreCase(fruitName)){
return new Banana();
}else{
System.out.println("can not find the fruit named:"+fruitName);
}
return null;
}
}
/**
*
* @author Jerval
* @date 2011-4-11
*/
public class MainClass {
public static void main(String[] args) {
Apple apple = (Apple) FruitFactory.getFruit("apple");
Banana banana = (Banana) FruitFactory.getFruit("banana");
apple.eat();
banana.eat();
}
}