ITeye博客

设计模式之简单工厂模式

bryande · 2010-04-12 23:18 · 企业架构 · Markdown

简单工厂模式是类的创建模式,又叫静态工厂模式,是工厂方法模式的一个特殊实现。

下面看一下源码实例

 

/**
 * 定义了一个接口,用于扩展
 * @author Administrator
 *
 */
public interface Shape {
	public void  draw();
	public void  erase();
}

 

/**
 * 实现了接口Shape的三角形类
 * @author Administrator
 *
 */
public class Triangle implements Shape {

	public void draw() {
		log("draw a triangle");
	}

	public void erase() {
		log("erase a triangle");
	}
	
	private void log(String msg){
		System.out.println(msg);
	}

}

 

/**
 * 实现了接口Shape的类
 * @author Administrator
 *
 */
public class Rectangle implements Shape {

	public void draw() {
		log("draw a rectangle");
	}

	public void erase() {
		log("erase a rectangle");
	}
	private void log(String msg){
		System.out.println(msg);
	}

}

 

/**
 * 实现了接口Shape的方法的类
 * @author Administrator
 *
 */
public class Square implements Shape {

	public void draw() {
		log("draw a square");
	}

	public void erase() {
		log("erase a square");
	}

	private void log(String msg){
		System.out.println(msg);
	}
}

 

public class SimpleFactory {
	/**
	 * 静态工厂方法
	 * @param type
	 * @return
	 * @throws Exception
	 */
	public static  Shape  getShape(String type)throws Exception{
		if("triangle".equalsIgnoreCase(type)){
			return new Triangle();
		}else if("rectangle".equalsIgnoreCase(type)){
			return new Rectangle();
		}else if("square".equalsIgnoreCase(type)){
			return new Square();
		}else {
			throw  new Exception();
		}
	}
	 
	
}

 

public class Test {
	/**
	 * 测试类
	 * @param args
	 */
	
	public static void main(String[] args) { 
		try {
				Shape  shape=SimpleFactory.getShape("rectangle");
				shape.draw();
				shape.erase();
				shape=SimpleFactory.getShape("square");
				shape.draw();
				shape.erase();
				shape=SimpleFactory.getShape("triangle");
				shape.draw();
				shape.erase();
			 
			} catch (Exception e) {
				e.printStackTrace();
			}
	}
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。