让一个工厂类去生产出对象 (new )来。
我们想要一个 形状,我们用工厂去生产出,圆形,方形。
java
package com.example.factory2;
public interface Shape {
void draw();
}
java
public class Square implements Shape {
@Override
public void draw() {
Log.d("LIU", "this is Square");
}
}
java
public class Circle implements Shape {
@Override
public void draw() {
Log.d("LIU","this is circle");
}
}
factory class:
java
public class ShapeFactory {
public Shape getShape (int type) {
if (type == 1) {
return new Circle();
} else if (type ==2) {
return new Square();
} else {
return null;
}
}
}
example and output:
java
ShapeFactory shapeFactory = new ShapeFactory();
Shape shape = shapeFactory.getShape(1);
shape.draw();
Shape shape2 = shapeFactory.getShape(2);
shape2.draw();
2024-10-02 22:23:47.705 14673-14673/com.example.factory2 D/LIU: this is circle
2024-10-02 22:23:47.706 14673-14673/com.example.factory2 D/LIU: this is Square
参考: 工厂模式 | 菜鸟教程