工廠模式分為簡單工廠、工廠模式、抽象工廠三種層級概念。簡單工廠不屬于23種設(shè)計(jì)模式,抽象工廠才是。
簡單工廠
簡單工廠主要就是通過工廠創(chuàng)建一個(gè)個(gè)不同的實(shí)例。
如:
abstract class Animal{
String name;
}
class Person extends Animal{
public Person(String name){
super();
this.name = name;
}
}
class Dog extends Animal{
public Dog(String name){
super();
this.name = name;
}
}
class Factory{
public Person getPerson(String name){
return new Person(name);
}
public Dog getDog(String name){
return new Dog(name);
}
}
工廠模式
工廠模式就是將單一工廠抽象化,通過不同的具體工廠來生產(chǎn)不同的實(shí)例。
abstract class Factory{
public abstract Animal create(String name);
}
class PersonFactory extends Factory{
public Animal create(String name){
return new Person(name);
}
}
class DogFactory extends Factory{
public Animal create(String name){
return new Dog(name);
}
}
抽象工廠
有時(shí)候,可能工廠單一生產(chǎn)一種實(shí)例滿足不了我們的需求,就比如人分為老人、小孩、青年人。狗也一樣。他們有不同的行為表現(xiàn)形式,但是他們都有行為方式,所以我們可以將這種行為方式抽象出來,在工廠中,分類對他們進(jìn)行處理。
abstract class property{
protected abstract void behavior();
}
abstract class Young extends property{
String name;
protected Young (String name){
this.name = name;
}
}
abstract class Child extends property{
String name;
protected Child (String name){
this.name = name;
}
}
class YoungPeople extends Young{
public YoungPeople (String name){
super(name);
}
protected void behavior(){
System.out.print("年輕人要工作");
}
}
class ChildPeople extends Child {
public ChildPeople (String name){
super(name);
}
protected void behavior(){
System.out.print("孩子們貪玩");
}
}
abstract class Factory{
public abstract Young createYoung(String name);
public abstract Child createChild(String name);
}
class PersonFactory extends Factory{
public Young createYoung(String name){
return new YoungPeople(name);
}
public Child createChild(String name){
return new ChildPeople(name);
}
}
總結(jié)
簡單工廠實(shí)質(zhì)上并沒有對對象進(jìn)行一個(gè)很好得分類作用,也沒有體現(xiàn)Java多態(tài)性(重載和重寫)
工廠模式通過不同的工廠對生產(chǎn)的不同實(shí)力進(jìn)行管理,在生產(chǎn)一種實(shí)例時(shí),只需要?jiǎng)?chuàng)建對應(yīng)的工廠,通過調(diào)用生產(chǎn)方法將對象生產(chǎn)出來,而且每次新增一種類型的對象,只需要新增一種工廠,簡單體現(xiàn)了Java的多態(tài)性,也很好進(jìn)行了解耦作用。
抽象工廠是工廠模式的一種進(jìn)階,此時(shí),我們不再以一個(gè)對象為單位,而是以一種類別為單位,此時(shí)我們不再以對象來進(jìn)行區(qū)分,而是以類型進(jìn)行區(qū)分。當(dāng)他們具有一定相同的行為特征時(shí),可以將這些行為特征提取出來,再具體分類處理,如人和狗都屬于動(dòng)物,但是他們都有自己的行為特征,而老人和小孩的行為特征也是不一樣的。這時(shí)候,人就是一種類別,而狗,又是另一種類別。總不能把人和狗混為一談的,哈哈~~
其實(shí)本次代碼還有很多可以優(yōu)化的地方,比如工廠可以采用單例模式,部分可以采用泛型優(yōu)化等。待后續(xù)熟練后優(yōu)化~工廠菜鳥隨筆感觸。