返回
Decorator模式:打造可扩展、灵活的应用
前端
2023-09-23 16:25:47
Decorator模式的优点
Decorator模式具有以下优点:
- 可扩展性: Decorator模式可以轻松地为现有对象添加新功能,而无需修改其源代码。
- 灵活性: Decorator模式可以动态地为对象添加功能,而无需重新编译代码。
- 解耦性: Decorator模式可以将对象的实现与它的功能分离,使代码更易于理解和维护。
Decorator模式的实现
在Java中,Decorator模式可以通过实现java.io.Serializable
接口来实现。在Python中,Decorator模式可以通过使用@
符号来实现。
Java中的Decorator模式
public interface Shape {
void draw();
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a rectangle");
}
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}
public class ShapeDecorator implements Shape {
private Shape shape;
public ShapeDecorator(Shape shape) {
this.shape = shape;
}
@Override
public void draw() {
shape.draw();
}
}
public class RedShapeDecorator extends ShapeDecorator {
public RedShapeDecorator(Shape shape) {
super(shape);
}
@Override
public void draw() {
shape.draw();
System.out.println("Drawing a red shape");
}
}
public class GreenShapeDecorator extends ShapeDecorator {
public GreenShapeDecorator(Shape shape) {
super(shape);
}
@Override
public void draw() {
shape.draw();
System.out.println("Drawing a green shape");
}
}
public class Main {
public static void main(String[] args) {
Shape rectangle = new Rectangle();
Shape circle = new Circle();
Shape redRectangle = new RedShapeDecorator(rectangle);
Shape greenCircle = new GreenShapeDecorator(circle);
redRectangle.draw();
greenCircle.draw();
}
}
Python中的Decorator模式
from functools import wraps
def shape(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("Drawing a shape")
func(*args, **kwargs)
return wrapper
def rectangle(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("Drawing a rectangle")
func(*args, **kwargs)
return wrapper
def circle(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("Drawing a circle")
func(*args, **kwargs)
return wrapper
@shape
def draw_rectangle():
pass
@shape
@rectangle
def draw_red_rectangle():
pass
@shape
@circle
def draw_green_circle():
pass
draw_rectangle()
draw_red_rectangle()
draw_green_circle()
结论
Decorator模式是一种强大的设计模式,它可以帮助我们轻松地扩展现有对象的