`
bryande
  • 浏览: 8476 次
  • 性别: Icon_minigender_1
  • 来自: 上海
最近访客 更多访客>>
社区版块
存档分类
最新评论
  • zxf_noimp: 有的拿就行了,知足吧
    无 语
  • lkj107: 建议跳过外包,直接去,何必要让人中间拦一下
    无 语
  • treblesoftware: 说个难听的话,上海有些人,宠物养护费一个月还花5500。
    无 语
  • bryande: sdao 写道你这头像一点都不低调哦 说的是你楼上吧。    ...
    无 语
  • bryande: 21xz 写道工作一年半 懂的还真不少啊,我到时候能有你一半就 ...
    无 语

设计模式之简单工厂模式

阅读更多

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

下面看一下源码实例

 

/**
 * 定义了一个接口,用于扩展
 * @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();
			}
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics