如何将矩阵操作类改造为Java装饰器模式实现?
装饰器模式改造矩阵操作类实现方案
你现有的矩阵操作类是基础的单一功能实现,要改成可叠加的装饰器模式,核心是通过持有组件实例+层级调用来实现功能组合,具体步骤和代码如下:
1. 修正并保留抽象组件接口
原接口的语法有小问题,修正后保持核心定义:
public interface MatrixOperation { int[][] apply(int[][] matrix); }
2. 实现基础组件(装饰器的底层载体)
需要一个不做任何操作的基础实现,作为装饰器叠加的起点:
public class IdentityMatrix implements MatrixOperation { @Override public int[][] apply(int[][] matrix) { // 直接返回原矩阵,作为基础操作 return matrix; } }
3. 创建抽象装饰器类
这是装饰器模式的核心,它实现MatrixOperation接口,同时持有一个MatrixOperation实例,用于传递操作:
public abstract class MatrixOperationDecorator implements MatrixOperation { protected MatrixOperation decoratedOperation; public MatrixOperationDecorator(MatrixOperation decoratedOperation) { this.decoratedOperation = decoratedOperation; } @Override public int[][] apply(int[][] matrix) { // 默认调用被装饰对象的操作,子类可重写扩展 return decoratedOperation.apply(matrix); } }
4. 将原有操作改造为具体装饰器
把你之前的SwitchRows、SwitchCols、Mult改成继承抽象装饰器的类,重写apply方法时,先调用被装饰对象的apply得到前置结果,再执行自身操作:
行交换装饰器
public class SwitchRowsDecorator extends MatrixOperationDecorator { public SwitchRowsDecorator(MatrixOperation decoratedOperation) { super(decoratedOperation); } @Override public int[][] apply(int[][] matrix) { // 先执行被装饰对象的操作,得到中间矩阵 int[][] processedMatrix = decoratedOperation.apply(matrix); // 再执行行交换操作 int[][] res = new int[2][2]; res[0] = processedMatrix[1]; res[1] = processedMatrix[0]; return res; } }
列交换装饰器
(修正原代码bug:原res[i][1] = matrix[1][0]应为processedMatrix[i][0])
public class SwitchColsDecorator extends MatrixOperationDecorator { public SwitchColsDecorator(MatrixOperation decoratedOperation) { super(decoratedOperation); } @Override public int[][] apply(int[][] matrix) { int[][] processedMatrix = decoratedOperation.apply(matrix); int[][] res = new int[2][2]; for (int i = 0; i < 2; i++) { res[i][0] = processedMatrix[i][1]; res[i][1] = processedMatrix[i][0]; } return res; } }
元素乘2装饰器
public class MultDecorator extends MatrixOperationDecorator { public MultDecorator(MatrixOperation decoratedOperation) { super(decoratedOperation); } @Override public int[][] apply(int[][] matrix) { int[][] processedMatrix = decoratedOperation.apply(matrix); int[][] res = new int[2][2]; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { res[i][j] = processedMatrix[i][j] * 2; } } return res; } }
5. 装饰器叠加使用示例
现在可以任意组合这些操作,比如先交换行,再乘2,最后交换列:
public class Main { public static void main(String[] args) { int[][] matrix = {{1,2},{3,4}}; // 组合操作:基础矩阵 → 交换行 → 乘2 → 交换列 MatrixOperation operation = new SwitchColsDecorator( new MultDecorator( new SwitchRowsDecorator( new IdentityMatrix() ) ) ); int[][] result = operation.apply(matrix); // 输出结果:原矩阵[[1,2],[3,4]] → 交换行后[[3,4],[1,2]] → 乘2后[[6,8],[2,4]] → 交换列后[[8,6],[4,2]] for (int[] row : result) { System.out.println(row[0] + " " + row[1]); } } }
关键说明
- 装饰器模式的核心是动态扩展功能,你可以随时新增新的装饰器类(比如元素加1、转置等),无需修改原有代码
- 所有装饰器都依赖抽象的
MatrixOperation接口,符合依赖倒置原则 - 叠加顺序会影响最终结果,调用时需要注意顺序
内容的提问来源于stack exchange,提问作者chucha
相关产品推荐
相关产品推荐

