java工厂模式

来源:互联网 发布:手机号批量加微信软件 编辑:程序博客网 时间:2024/06/06 11:58

工厂模式

方法步骤:

1.创建一个接口
2.创建实现相同接口的具体类
3.创建工厂根据给定的信息生成具体类的对象。

4.使用工厂通过传递类型等信息来获取具体类的对象。

package sa;


 interface Shape {//创建一个接口
  void draw();
}
 class Rectangle implements Shape {//创建实现相同接口的具体类


  @Override
  public void draw() {
     System.out.println("Inside Rectangle::draw() method.");
  }
}
 class Square  implements Shape {//创建实现相同接口的具体类


  @Override
  public void draw() {
     System.out.println("Inside Square::draw() method.");
  }
}
 class Circle implements Shape {//创建实现相同接口的具体类


  @Override
  public void draw() {
     System.out.println("Inside Circle::draw() method.");
  }
}
 class ShapeFactory {//创建工厂根据给定的信息生成具体类的对象。


  //use getShape method to get object of type shape 
  public Shape getShape(String shapeType){
     if(shapeType == null){
        return null;
     }        
     if(shapeType.equalsIgnoreCase("CIRCLE")){
        return new Circle();


     } else if(shapeType.equalsIgnoreCase("RECTANGLE")){
        return new Rectangle();


     } else if(shapeType.equalsIgnoreCase("SQUARE")){
        return new Square();
     }


     return null;
  }
}

public class Factory {//使用工厂通过传递类型等信息来获取具体类的对象。



public static void main(String[] args) {
// TODO Auto-generated method stub

 
     ShapeFactory shapeFactory = new ShapeFactory();
     Shape shape1 = shapeFactory.getShape("CIRCLE");
     shape1.draw();
     Shape shape2 = shapeFactory.getShape("RECTANGLE");
     shape2.draw();
     Shape shape3 = shapeFactory.getShape("SQUARE");
     shape3.draw();
}


}

测试结果

Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.

1 0
原创粉丝点击