工廠模式
工廠模式就是專門負責將大量有共同接口的類實例化,而且不必事先知道每次是要實例化哪一個類的模式。它定義一個用於創建對象的接口,由子類決定實例化哪一個類。
java 例子如下:
package com.lyis.patterns.factory;
/**
* 水果接口
*/
public interface Fruit {
/**
* 獲取水果名稱
*
* @return
*/
public String getFruitName();
/**
* 獲取水果描述
*
* @return
*/
public String getDescription();
}
package com.lyis.patterns.factory;
/**
* 蘋果(具體水果)
*/
public class Apple implements Fruit {
public String getFruitName() {
return "Apple";
}
public String getDescription() {
return "Tastes great!";
}
}
package com.lyis.patterns.factory;
/**
* 葡萄(具體水果)
*/
public class Grape implements Fruit {
public String getFruitName() {
return "Grape";
}
public String getDescription() {
return "Very sweet!";
}
}
package com.lyis.patterns.factory;
/**
* 水果工廠
*/
public class FruitFactory {
public static Fruit getFruit(String name) {
if ("apple".equals(name)) {
return new Apple();
}
if ("grape".equals(name)) {
return new Grape();
}
return null;
}
}
package com.lyis.patterns.factory;
/**
* 工廠模式測試
*/
public class Test {
/**
* 輸出水果信息
*
* @param fruit
* 水果對象
*/
public void display(Fruit fruit) {
if (fruit == null) {
return;
}
System.out.println("Name: " + fruit.getFruitName());
System.out.println("Desc: " + fruit.getDescription());
}
public static void main(String[] args) {
Test test = new Test();
// 獲取蘋果對象
Fruit fruit = FruitFactory.getFruit("apple");
test.display(fruit);
// 獲取葡萄對象
fruit = FruitFactory.getFruit("grape");
test.display(fruit);
}
}