[关键字]:java,设计模式,简单工厂,《java与模式》
[环境]:StarUML + JDK6
[作者]:Winty ([email protected])
简单工厂模式:
代码:
/**
*简单工厂测试
*@version 2009-3-25
*@author Winty(
[email protected])
*/
package pattern.simplefactory;
public class SimpleFactory{
public static void main(String[] args){
Shape shape;
try{
shape = ArtTracer.factory("circle");
shape.draw();
shape.erase();
shape = ArtTracer.factory("square");
shape.draw();
shape.erase();
shape = ArtTracer.factory("triangle");
shape.draw();
shape.erase();
//未知图形类型
shape = ArtTracer.factory("unknownShape");
shape.draw();
shape.erase();
}catch(BadShapeException e){
System.out.println(e.getMessage());
}
}
}
/**
*简单工厂:绘图员
*/
class ArtTracer{
public static Shape factory(String type)throws BadShapeException{
if(type.equalsIgnoreCase("Circle")){
return new Circle();
}else if(type.equalsIgnoreCase("Square")){
return new Square();
}else if(type.equalsIgnoreCase("Triangle")){
return new Triangle();
}else{
throw new BadShapeException(type);
}
}
}
/**
*抽象产品
*/
abstract class Shape{
public abstract void draw();
public abstract void erase();
}
/**
*具体产品
*/
class Circle extends Shape{
public void draw(){
System.out.println("Circle draw");
}
public void erase(){
System.out.println("Circle erase");
}
}
/**
*具体产品
*/
class Square extends Shape{
public void draw(){
System.out.println("Square draw");
}
public void erase(){
System.out.println("Square erase");
}
}
/**
*具体产品
*/
class Triangle extends Shape{
public void draw(){
System.out.println("Triangle draw");
}
public void erase(){
System.out.println("Triangle erase");
}
}
/**
*辅助类:当输入的类为不支持的图形时,抛出异常
*/
class BadShapeException extends Exception{
public BadShapeException(String type){
super(type + ":不支持的图形");
}
}