2.抽象工廠模式 和 工廠模式對比
簡單來說,抽象工廠模式正如名字所示,即對工廠進行抽象,比起工廠模式多了一層抽象而已。在《Design Pattern Explains》書中,作者說的很到位,設計模式即是“Find what varies and encapsulate it”, 翻譯過來即 封裝起那些變換的事物。
如下所示(圖引用於here):抽象工廠模式中把 產生A,B的工廠,抽象成一個 類,類中通過方法來產生有關聯的產品,比如圓形,方形。而每個方法,都是依賴工廠模式實現
CODE 1: Factory Pattern
public interface Shape{
void draw();
}
public class Rectangle implements Shape{
public void draw(){
System.out.println("Inside Square::draw() method.");
}
}
public class CircleimplementsShape{
public void draw(){
Systerm.out.println("Inside Circle::draw() method");
}
}
public class ShapeFactory{
public shape getShape (String shapeType){
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE")){
return new Circle();
}else if(ShapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
}else if(ShapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
return null;
}
}
// client code
public class FactoryPatternDemo{
public static void main(String[] args){
ShapeFactory shapeFactory = new ShapeFactory();
Shape shape1 = shapeFactory.getShape("CIRCLE");
shape1.draw();
Shape shape2 = shapeFactory.getShape("RECTANGLE");
shape2.draw();
Shape shape3 = shapeFactory.getShape("SQUARE");
shape3.draw();
}
}
CODE2: ABSTRACT Fatory PAttern
public interface Shape{
void draw();
}
public class Rectangle implements Shape{
public void draw(){
System.out.println("Inside Square::draw() method.");
}
}
public class Circle implements Shape{
public void draw(){
Systerm.out.println("Inside Circle::draw() method");
}
}
public interface <span style="color:#cc0000;">Color</span>{
void draw();
}
public class Red implements Color{
public void draw(){
System.out.println("Inside Red::fill() method.");
}
}
public class Green implements Color{
public void draw(){
Systerm.out.println("Inside Green::fill() method");
}
}
public abstract class AbstractFactory{
abstract Color getColor(String color);
abstract Shape getShape(String shape);
}
public class ShapeFactory extends AbstractFactory{
public shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE")){
return new Circle();
}else if(ShapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
}else if(ShapeType.equalsIgnoreCase("SQUARE")){
return new Square();
}
return null;
}
// override
Color getColor(String color){
return null;
}
}
public class ColorFactory extends AbstractFactory{
//override
public Shape getShape(String shapeType){
return null;
}
Color getColor(String color){
if(color == null){
return null;
}
if(color.equalsIgnoreCase("RED")){
return new Red();
}else if(color.equalsIgnoreCase("Green")){
return new Green();
}
}
}
public class FactoryProducer{
public static AbstractFactory getFactory(String chioce){
if(choice.equalsIgnoreCase("SHAPE")){
return new ShapeFactory();
}else if(choice.equalsIgnoreCase("COLOR")){
return new ColorFactory();
}
return null;
}
}