工厂模式简介内容参考易百教程
1、创建接口
2、创建实现接口的具体类,实现接口并重写接口中的方法。(对于抽象类,可以不用实现接口中的所有方法,可以又他的子类实现。普通的实现类,必须实现接口中的所有方法。)
3、创建工厂类
4、创建演示类,通过工厂类获取对象
流程如下:演示类中初始化工厂类,通过工厂类创建对象,对象实现了接口中的方法。
1、创建Shape接口
Shape.java
public interface Shape {
void draw();
}
2.创建实现接口的具体类
Rectangle.java
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.print(" Rectangle --- implements Shape");
}
}
Square.java
public class Square implements Shape {
@Override
public void draw() {
System.out.print("Square --- implements Shape");
}
}
Circle.java
public class Circle implements Shape {
@Override
public void draw() {
System.out.print(" Circle --- implements Shape");
}
}
3、创建工厂类
ShapeFactory.java
public class ShapeFactory {
public Shape getShape(String shapetype){
if(shapetype == null){
System.out.println("shape type is null");
return null;
}
if(shapetype.equalsIgnoreCase("Rectangle")){
System.out.println("Rectangle --- is shape type");
return new Rectangle();
}else if (shapetype.equalsIgnoreCase("Square")){
System.out.println("Square --------- is shape type");
return new Square();
}else if(shapetype.equalsIgnoreCase("Circle")){
System.out.println("Circle is --- shape type");
return new Circle();
}else {
System.out.println("not found this method");
}
return null;
}
}
4、创建创建演示类,通过工厂类创建对象
FactoryPatternDemo.java
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Shape shape1 = shapeFactory.getShape("Rectangle");
shape1.draw();
System.out.println("1-------------------------------2");
Shape shape2 = shapeFactory.getShape("Circle");
shape2.draw();
System.out.println("2-------------------------------2");
Shape shape3 = shapeFactory.getShape("Square");
shape3.draw();
}
}
结果如下:
Rectangle --- is shape type
Rectangle --- implements Shape1-------------------------------2
Circle is --- shape type
Circle --- implements Shape2-------------------------------2
Square --------- is shape type
Square --- implements Shape
Process finished with exit code 0
参考链接:Java工厂设计模式