命令模式

本文介绍了一种利用命令模式处理数组元素的方法。通过定义Command接口并由PrintCommand和AddCommand两个类实现,分别实现了数组元素的打印和求和功能。ProcessArray类用于执行具体命令,CommandTest类作为测试入口展示不同命令的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

建立一个接口:
1
2
3
4
5
package com;
 
public interface Command {
    void process(int[] target);
}
两个类继承这个接口:
1
2
3
4
5
6
7
8
9
10
11
package com;
 
public class PrintCommand implements Command {
    public void process(int[] target)
    {
        for(int tmp:target)
        {
            System.out.println("迭代输出数组的元素:"+tmp);
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
package com;
 
public class AddCommand implements Command {
    public void process(int[] target)
    {
        int sum=0;
        for(int tmp:target)
        {
            sum+=tmp;
        }
        System.out.println("数组元素的总和是:"+sum);
    }
}
定义数组的处理类:
1
2
3
4
5
6
7
8
package com;
 
public class ProcessArray {
    public void process(int[] target,Command cmd)
    {
        cmd.process(target);
    }
}
测试程序:(传入不同的类对象,实现选择不同的处理方法)
1
2
3
4
5
6
7
8
9
10
11
package com;
 
public class CommandTest {
    public static void main(String[] args)
    {
        ProcessArray pa=new ProcessArray();
        int[] target={3,-4,6,4};
        pa.process(target, new PrintCommand());
        pa.process(target, new AddCommand());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值