介绍
专门定义一个类用来创建其它类的实例,被创建的实例通常都具有共同的父类。
角色
工厂角色: 可以被客户端调用,其内部用于负责创建具体的对象。
抽象产品类:描述了所有实例的公共接口。
具体产品类:实现抽象产品的接口,是工厂角色中要创建的具体实例。
UML
总结
简单工厂模式的优点从上面两种方式对比可以看出,工厂角色负责产生具体的实例对象,所以在工厂类中需要有必要的逻辑,通过客户的输入能够得到具体创建的实例;所以客户端就不需要感知具体对象是如何产生的,只需要将必要的信息提供给工厂即可。
缺点:简单工厂模式是违反“开闭原则”,即对扩展开放,对修改关闭;因为如果要新增具体产品,就需要修改工厂类的代码。
实例
package HomeWork1;
public interface Shape {
public void printShape();
}
package HomeWork1;
public class Round implements Shape{
public void printShape(){
System.out.print("this is Round");
}
}
package HomeWork1;
public class Rectangle implements Shape{
public void printShape(){
System.out.print("this is Rectangle");
}
}
package HomeWork1;
public class Line implements Shape{
public void printShape(){
System.out.print("this is Line");
}
}
package HomeWork1;
public class ShapeFactory {
public Shape createShape(String type){
Shape s=null;
if(type.equals("Round")) s=new Round();
else if(type.equals("Rectangle")) s=new Rectangle();
else if(type.equals("Line")) s=new Line();
return s;
}
}
package HomeWork1;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Client {
public void draw(Shape s){
System.out.println("I draw a Shape");
s.printShape();
}
public void showlist(List<Shape> shape){
System.out.println();
System.out.println("现在画板里有:");
Shape t;
for(int i=0;i<shape.size();i++){
t=shape.get(i);
System.out.print("<");
t.printShape();
System.out.print(">");
if((i+1)%2==0) System.out.println();
}
System.out.println();
}
public void printMenu(){
System.out.println("1:添加图形");
System.out.println("2:删除图形");
System.out.println("3:退出");
}
public List<Shape> delete(List<Shape> shape){
shape.remove(shape.size()-1);
return shape;
}
public void operate(){
ShapeFactory sf=new ShapeFactory();
List<Shape> shape=new ArrayList<>();
Scanner scanner=new Scanner(System.in);
while(true)
{ //System.out.println("----------------------------------------------");
System.out.println("请选择你需要的功能:");
printMenu();
int id=scanner.nextInt();
switch(id){
case 1: System.out.println("请输入你要画的图形:");
String type=scanner.next();
Shape s=sf.createShape(type);
draw(s);
shape.add(s);
showlist(shape);
break;
case 2:System.out.print("删除上一次所画的图形:");
shape=delete(shape);
showlist(shape);
break;
case 3:return;
default:System.out.println("请输入正确的服务号!");
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Client c=new Client();
c.operate();
}
}