一起学Java设计模式--简单工厂模式(不在23中设计模式之内)

(1) 简单工厂模式

使用简单工厂模式设计一个可以创建不同几何形状(Shape)的绘图工具类,如可创建圆形(Circle)、方形(Rectangle)和三角形(Triangle) 对象,每个几何图形都要有绘制draw()和擦除erase()两个方法,要求在绘制不支持的几何图形时,提示一个UnsupportedShapeException,绘制类图并编程实现。

一起学Java设计模式--简单工厂模式(不在23中设计模式之内)_第1张图片

//抽象图形
public interface Shape{
	void draw();
	void erase();
} 
public class Circle implements Shape{
	public void draw(){
		System.out.println("Circle draw!");
	}	
	public void erase(){
		System.out.println("Circle erasing!");
	}
} 
public class Rectangle implements Shape{
	public void draw(){
		System.out.println("Rectangle draw!");
	}
	public void erase(){
		System.out.println("Rectangle erasing!");
	}
} 
public class Triangle implements Shape{
	public void draw(){
		System.out.println("Triangle draw!");
	}
	public void erase(){
		System.out.println("Triangle erasing!");
	}
}
//工厂
import java.lang.*;

public class ShapeFactory{
	public static Shape produceShape(String shapeName) 
			throws UnsupportedShapeException{
		if(shapeName.equals("circle")){
			return new Circle();
		}else if(shapeName.equals("rectangle")){
			return new Rectangle();
		}else if(shapeName.equals("triangle")){
			return new Triangle();
		}else{
			throw new UnsupportedShapeException();
		}
	}
}
class UnsupportedShapeException extends Exception{  
	public String toString(){
		return "绘制不支持该几何图形!";
	}
	
}

public class ShapeClient{
	public static void main(String[] args){
		Shape circle = null;
		Shape rectangle = null;
		Shape triangle = null;
		
		Shape diamond = null;
		try{
			circle = ShapeFactory.produceShape("circle");
			rectangle = ShapeFactory.produceShape("rectangle");
			triangle = ShapeFactory.produceShape("triangle");
			
			
		circle.draw();
		circle.erase();
		
		rectangle.draw();
		rectangle.erase();
		
		triangle.draw();
		triangle.erase();
		
		
		}catch(UnsupportedShapeException e){
			e.printStackTrace(); 
		}
		
		try{
			diamond = ShapeFactory.produceShape("diamond");
			
			diamond.draw();
			diamond.erase();
		}catch(UnsupportedShapeException e){
			e.printStackTrace();
		}
		
		
		
	}
}

运行结果:

一起学Java设计模式--简单工厂模式(不在23中设计模式之内)_第2张图片

你可能感兴趣的:(Java设计模式)