設計模式之—簡單工廠方法(StaticFactory )-Java實現

工廠模式一共分爲三種,分別是:簡單工廠模式,工廠方法模式和抽象工廠模式。

先來說說簡單工廠模式,簡單工廠模式一般不在實際中是用,因爲它的擴展性不好,例如我們添加一個新的類,而需要去更改現有的類,爲了一個新需求去更改原有類的代碼,那麼就有可能引入新的bug,如果是新加一個類,而不改變原有類這就可以非常有效地降低引入新bug的風險,因此,擴展性是非常重要的。下面是一個簡單工廠模式的例子:

public interface Person{        
}  
public class Student implements Person{  
}  
public class Teacher implements Person{  
}  
public class Farmer implements Person{  
}  
public class PersonFactory  
{  
    public static Person factory(String whichPerson)  
    {  
        if (whichPerson.equalsIgnoreCase("student"))  
        {  
            return new Student();  
        }  
        else if (whichPerson.equalsIgnoreCase("teacher"))  
        {  
            return new Teacher();  
        }  
        else if (whichPerson.equalsIgnoreCase("farmer"))  
        {  
            return new Farmer();  
        }  
        else  
        {  
            return new null;  
        }  
    }  
}  

上面的代碼很容易看懂,想要得到一個Student,用Student student = PersonFactory .factory("student");這句話就行了。這樣看來,上面的代碼已經實現了工廠模式,事實也的確如此,但是問題就在於先前所提到的擴展性,當我們想要這個工廠新增hunter的時候,必須做下面兩件事情,第一,寫一個Hunter類,它實現了接口Person,然後再更改PersonFactory,讓其能夠生產Hunter,如下:

public interface Person{        
}  
public class Student implements Person{  
}  
public class Teacher implements Person{  
}  
public class Farmer implements Person{  
}
public class Hunter implements Person{
}
public class PersonFactory  
{  
    public static Person factory(String whichPerson)  
    {  
        if (whichPerson.equalsIgnoreCase("student"))  
        {  
            return new Student();  
        }  
        else if (whichPerson.equalsIgnoreCase("teacher"))  
        {  
            return new Teacher();  
        }  
        else if (whichPerson.equalsIgnoreCase("farmer"))  
        {  
            return new Farmer();  
        }else if(whichPerson.equalsIgnoreCase("hunter"))
{
return new Hunter();
}
        else  
        {  
            return new null;  
        }  
    }  
}  

這樣就違背了我們先前說的只能新加類,不能修改現有類的原則,如何實現工廠模式呢?而工廠方法模式(FactoryMethod)就解決了這個問題——待續



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