通常在回答xxx模式与yyy模式的区别,第一印象就是要分清楚他们两是不是同一类。
下面给大家整理设计模式分类:
从图中可以看出,代理模式和装饰器膜还是都属于结构型设计模式。
下面我们通过代码案例来看这两个设计模式到底有什么区别:
代理模式案例:
// 定义接口
interface Image {
void display();
}
// 被代理类
class RealImage implements Image {
private String filename;
public RealImage(String filename) {
this.filename = filename;
loadFromDisk();
}
private void loadFromDisk() {
System.out.println("Loading image from disk: " + filename);
}
public void display() {
System.out.println("Displaying image: " + filename);
}
}
// 代理类
class ImageProxy implements Image {
private String filename;
private RealImage realImage;
public ImageProxy(String filename) {
this.filename = filename;
}
public void display() {
if (realImage == null) {
realImage = new RealImage(filename);
}
realImage.display();
}
}
// 使用代理类
public class ProxyPatternExample {
public static void main(String[] args) {
Image image = new ImageProxy("image.jpg");
image.display();
}
}
装饰器模式案例:
// 定义接口
interface Shape {
void draw();
}
// 具体实现类
class Circle implements Shape {
public void draw() {
System.out.println("Drawing a circle");
}
}
// 装饰器类
abstract class ShapeDecorator implements Shape {
protected Shape decoratedShape;
public ShapeDecorator(Shape decoratedShape) {
this.decoratedShape = decoratedShape;
}
public void draw() {
decoratedShape.draw();
}
}
// 具体装饰器类
class RedShapeDecorator extends ShapeDecorator {
public RedShapeDecorator(Shape decoratedShape) {
super(decoratedShape);
}
public void draw() {
decoratedShape.draw();
setRedBorder();
}
private void setRedBorder() {
System.out.println("Adding red border");
}
}
// 使用装饰器类
public class DecoratorPatternExample {
public static void main(String[] args) {
Shape circle = new Circle();
ShapeDecorator redCircle = new RedShapeDecorator(new Circle());
circle.draw();
redCircle.draw();
}
}
这两个例子分别展示了代理模式和装饰器模式的使用方式和区别。
代理模式和装饰器模式是两种不同的设计模式,虽然它们有一些共同的特点,但是在使用方式和实现上有一些区别。
区别如下:
代理模式在项目中,用的最多的就是动态代理(比如:JDK、CGLib)。
装饰器模式基本上都是用在老项目中,或者说对已经完好的功能进行功能增强。
记住核心点:访问权限、功能增强
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有