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

(1) 简单工厂模式

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

//抽象图形
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();
		}
		
		
		
	}
}

运行结果:


  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值