工廠模式主要是為創建對象提供過渡接口,以便將創建對象的具體過程屏蔽隔離起來,達到提高靈活性的目的。
在下面的章節中,我們將展示如何使用工廠模式來創建對象。
由工廠模式創建的對象將是形狀的物體,如圓形,矩形。
首先,我們設計代表形狀的接口。
public interface Shape {
void draw();
}
然後,我們創建具體的類實現該接口。
Rectangle.java
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
Square.java
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
Circle.java
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
核心工廠模式是工廠類。下面的代碼演示如何創建一個工廠類Shape對象。
該ShapeFactory類創建基於傳遞到getShape()方法的字符串值Shape對象。如果字符串值是圓,它會創建一個Circle對象。
public class ShapeFactory {
//use getShape method to get object of type shape
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;
}
}
下面的代碼有mian方法,它采用工廠類傳遞一個信息,如類型,以獲得具體類的對象。
public class Main {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
//get an object of Circle and call its draw method.
Shape shape1 = shapeFactory.getShape("CIRCLE");
//call draw method of Circle
shape1.draw();
//get an object of Rectangle and call its draw method.
Shape shape2 = shapeFactory.getShape("RECTANGLE");
//call draw method of Rectangle
shape2.draw();
//get an object of Square and call its draw method.
Shape shape3 = shapeFactory.getShape("SQUARE");
//call draw method of circle
shape3.draw();
}
}
原文地址:http://www.manongjc.com/article/135.html