python 实现
`
import abc
抽象类,定义方法,不具体实现方法,继承类具体实现方法
class Shape(metaclass=abc.ABCMeta):
@abc.abstractmethod
def draw(self):
pass
工厂类
class Rectangle(Shape):
"""A simple"""
def draw(self):
print("Inside Rectangle::draw() method.")
工厂类
class Square:
"""A simple localizer a la gattext"""
def draw(self):
print("Inside Square::draw() method.")
class ShapeFactory:
def getShape(self, shapeType: str):
if shapeType == None:
return
if shapeType.upper() == "RECTANGLE":
return Rectangle()
elif shapeType.lower() == "square":
return Square()
return
if name == 'main':
# 实例化工厂类
shapeFactory = ShapeFactory()
shape1 = shapeFactory.getShape("rectangle")
shape1.draw()
shape2 = shapeFactory.getShape("square")
shape2.draw()
`
java 实现
main.java
`
public interface Shape {
void draw();
}
public class Rectangle implements Shape{
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
public class ShapeFactory {
public Shape getShape(String shapeType){
if (shapeType==null){
return null;
}
if (shapeType.equalsIgnoreCase("square")){
return new Square();
}
else if (shapeType.equalsIgnoreCase("rectangle")){
return new Rectangle();
}
return null;
}
}
public class Main {
public static void main(String[] args){
// 创建工厂类实例
ShapeFactory shapeFactory = new ShapeFactory();
// 使用工厂类实例 方法获取具体的 细节类
Shape shape1 = shapeFactory.getShape("Rectangle");
// 细节类调用
shape1.draw();
// 使用工厂类实例 方法获取具体的 细节类
Shape shape2 = shapeFactory.getShape("square");
// 细节类调用
shape2.draw();
}
}
`