第110章

bookmark

小A:“工廠方法模式涉及到哪些角色?”

大B:工廠方法模式的角色有:抽象工廠(Creator)角色、具體工廠(ConcreteCreator)角色、抽象產品(Product)角色、具體產品(ConcreteProduct)角色。

抽象工廠(Creator)角色:是工廠方法模式的核心,與應用程序無關。任何在模式中創建的對象的工廠類必須實現這個接口。

具體工廠(ConcreteCreator)角色:這是實現抽象工廠接口的具體工廠類,包含與應用程序密切相關的邏輯,並且受到應用程序調用以創建產品對象。

有兩個這樣的角色:BulbCreator與TubeCreator。

抽象產品(Product)角色:工廠方法模式所創建的對象的超類型,也就是產品對象的共同父類或共同擁有的接口。

具體產品(ConcreteProduct)角色:這個角色實現了抽象產品角色所定義的接口。某具體產品有專門的具體工廠創建,它們之間往往一一對應。

//產品Plant接口

publicinterfacePlant{}

//具體產品PlantA,PlantB

publicclassPlantAimplementsPlant{

publicPlantA(){

System.out.println(“createPlantA!”);

}

publicvoiddoSomething(){

System.out.println(“PlantAdosomething……”);

}

}

publicclassPlantBimplementsPlant{

publicPlantB(){

System.out.println(“createPlantB!”);

}

publicvoiddoSomething(){

System.out.println(“PlantBdosomething……”);

}

}

//產品Fruit接口

publicinterfaceFruit{}

//具體產品FruitA,FruitB

publicclassFruitAimplementsFruit{

publicFruitA(){

System.out.println(“createFruitA!”);

}

publicvoiddoSomething(){

System.out.println(“FruitAdosomething……”);

}

}

publicclassFruitBimplementsFruit{

publicFruitB(){

System.out.println(“createFruitB!”);

}

publicvoiddoSomething(){

System.out.println(“FruitBdosomething……”);

}

}

//抽象工廠方法

publicinterfaceAbstractFactory{

publicPlantcreatePlant();

publicFruitcreateFruit();

}

//具體工廠方法

publicclassFactoryAimplementsAbstractFactory{

publicPlantcreatePlant(){

returnnewPlantA();

}

publicFruitcreateFruit(){

returnnewFruitA();

}

}

publicclassFactoryBimplementsAbstractFactory{

publicPlantcreatePlant(){

returnnewPlantB();

}

publicFruitcreateFruit(){

returnnewFruitB();

}

}

第154章第146章第125章第114章第204章第114章第151章第119章第173章第134章第39章第171章第222章第87章第183章第137章第206章第211章第217章第75章第163章第196章第202章第23章第66章第193章第166章第173章第88章第176章第18章第185章第216章第228章第176章第38章第61章第126章第117章第85章第99章第205章第102章第169章第100章第9章第207章第146章第116章第133章第114章第194章第197章第217章第213章第213章第42章第136章第60章第26章第41章第114章第83章第59章第117章第115章第132章第70章第75章第76章第46章第166章第83章第55章第179章第108章第41章第68章第71章第173章第168章第88章第169章第20章第25章第220章第187章第31章第142章第35章第140章第222章第142章第103章第72章第10章第98章第138章第93章
第154章第146章第125章第114章第204章第114章第151章第119章第173章第134章第39章第171章第222章第87章第183章第137章第206章第211章第217章第75章第163章第196章第202章第23章第66章第193章第166章第173章第88章第176章第18章第185章第216章第228章第176章第38章第61章第126章第117章第85章第99章第205章第102章第169章第100章第9章第207章第146章第116章第133章第114章第194章第197章第217章第213章第213章第42章第136章第60章第26章第41章第114章第83章第59章第117章第115章第132章第70章第75章第76章第46章第166章第83章第55章第179章第108章第41章第68章第71章第173章第168章第88章第169章第20章第25章第220章第187章第31章第142章第35章第140章第222章第142章第103章第72章第10章第98章第138章第93章