設計模式一:簡單工廠模式

簡單工廠模式屬於類的創建型模式,又叫做靜態工廠方法模式。通過專門定義一個類來負責創建其它類的實例,被創建的實例通常都具有共同的父類。

模式中包含的角色及職責:

1.工廠角色;

       簡單工廠模式的核心,它負責實現創建所有實例的內部邏輯。

/**
 * 簡單工廠類
 * @author guosheng
 *
 */
public class AnimalFactory {

    public static Animal getAnimal(String className){
        try {
            Class animal = Class.forName(className);
            return (Animal)animal.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}


2.抽象角色:簡單工廠模式所創建的所有對象的父類。

/**
 * 動物接口
 * 郭勝
 * @author guosheng
 *
 */
public interface Animal {
    
    public void move();

}

3.具體產品角色:簡單工廠模式所創建的具體實例對象

/**
 * 貓
 * @author guosheng
 *
 */
public class Cat implements Animal{

    public void move(){
        System.out.println("貓:四隻腿,走走走");
    }
}

/**
 * 狗
 * @author guosheng
 *
 */
public class Dog implements Animal{

    public void move(){
        System.out.println("狗:四隻腿,走走走");
    }
}

獲取:

/**
 * 簡單工廠類
 *
 * @author guosheng
 *
 */
public class MainMethod {

    public static void main(String[] args) {
        Animal dog = AnimalFactory.getAnimal("Dog");
        dog.move();
        Animal cat = AnimalFactory.getAnimal("Cat");
        cat.move();
    }
}

優缺點:

優:在這個模式中,工廠類是整個模式的關鍵。它包含必要的判斷邏輯,能夠根據外界給定的信息,決定究竟應該創建哪個具體類的對象。用戶在使用時可以直接根據工廠類去創建所需的實例,而無需瞭解這些對象是如何創建以及如何組織的,有利於整個軟件體系結構的優化。

缺:簡單工廠模式的缺點也正體現在其工廠類上,由於工廠類集中了所有實例的創建邏輯,所以高內聚方面做的並不好。當系統中的具體產品類不斷增多時,可能會出現要求工廠類也要做相應的修改,擴展性並不很好。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章