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

來源:互聯網
上載者:User

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

先來說說簡單原廠模式,簡單原廠模式一般不在實際中是用,因為它的擴充性不好,例如我們添加一個新的類,而需要去更改現有的類,為了一個新需求去更改原有類的代碼,那麼就有可能引入新的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;  
        }  
    }  
}  

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



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.