1。简单工厂模式
简单工厂模式就是由一个工厂类根据参数来决定创立出那一种产品类的实例。下面的UML类图就精确定义了简单工厂模式的结构。
例如:
代码:
package com.javapatterns.simplefactory.exercise;
public class ArtTracer
{
public Shape factory(String which) throws BadShapeException
{
if (which.equalsIgnoreCase("circle"))
{
return new Circle();
}
else if (which.equalsIgnoreCase("square"))
{
return new Square();
}
else if (which.equalsIgnoreCase("triangle"))
{
return new Triangle();
}
else
{
throw new BadShapeException(which);
}
}
}
package com.javapatterns.simplefactory.exercise;
public interface Shape
{
void draw();
void erase();
}
package com.javapatterns.simplefactory.exercise;
public class Square implements Shape
{
public void draw()
{
System.out.println("Square.draw()");
}
public void erase()
{
System.out.println("Square.erase()");
}
}
package com.javapatterns.simplefactory.exercise;
public class BadShapeException extends Exception
{
public BadShapeException(String msg)
{
super(msg);
}
}
描图员(Art Tracer)系统使用方法如下
try
{
ArtTracer art = new ArtTracer();
art.factory("circle");
art.factory("square");
art.factory("triangle");
art.factory("diamond");
}
catch(BadShapeException e)
{
...
}
2。工厂模式
3。抽象工厂模式
posted on 2006-02-10 14:42
googlor 阅读(187)
评论(0) 编辑 收藏 所属分类:
J2EE