简单工厂模式学习
工厂模式(Factory Pattern)又被称为静态工厂方法模式,主要实现是有工厂类,产品抽象类以及具体产品类组成。其中工厂类的主要作用在于针对不同的 产品生产在抽象类引用下的具体产品的实例。例如生产不同的形状时,有抽象类Shape,具体产品类Rectangle、Circle、Triangle等,以及实例化各个具体产品并向外提供引用的工厂类。
先创建一个抽象产品出来的接口Shape只有一个功能
public interface{
void onDraw();
void setBound(int... bounds);
}
创建具体产品的类
public class Rectangle implements Shape{
private int width;
private int height;
@Override
public void onDraw() {
System.out.println("draw rectangle:"+width+"*"+height);
}
@Override
public void setBound(int... bounds){
this.width =bounds[0];
this.height =bounds[1];
}
}
public class Triangle implements Shape{
private int bound1;
private int bound2;
private int bound3;
@Override
public void onDraw() {
System.out.println("draw triangle:"+bound1+"*"+bound2+"*"+bound3);
}
@Override
public void setBound(int... bounds){
this.bound1=bounds[0];
this.bound2=bounds[1];
this.bound3=bounds[2];
}
}
public class Circle implements Shape{
private int radium;
@Override
public void onDraw() {
System.out.println("draw Circle:"+radium);
}
@Override public void setBound(int... bounds) { this.radium = bounds[0]; }
}
创建工厂类
public class ShapeFactory {
/**
*@param type 0:rectangle 1:triangle 2:circle
* */
public Shape creteShape(int type){
Shape shape = null;
switch (type){
case 0:
shape = new Rectangle();
break;
case 1:
shape = new Triangle();
break;
case 2:
shape = new Circle();
break;
}
return shape;
}
}
创建工厂实例类
public class FactoryDemo {
private ShapeFactory mShapeFactory;
public FactoryDemo(){
mShapeFactory = new ShapeFactory();
}
public void onDrawrect(int width,int height){
Shape rectangle = mShapeFactory.creteShape(0);
rectangle.setBound(width,height);
rectangle.onDraw();
}
public void onDrawTriangle(int bound1,int bound2,int bound3){
Shape triangle = mShapeFactory.creteShape(1);
triangle.setBound(bound1,bound2,bound3);
triangle.onDraw();
}
public void onCircle(int radium){
Shape circle = mShapeFactory.creteShape(2);
circle.setBound(radium);
circle.onDraw();
}
}
自此就完成了图形的简单工厂模式。可以在main中调用工厂实例来实现。
这里用了android的activity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FactoryDemo demo = new FactoryDemo();
demo.onDrawrect(10,20);
demo.onCircle(6);
demo.onDrawTriangle(3,4,5);
}
结果如下