Henry Sun

没有所谓的偶然,一切皆是因果

博客园 首页 新随笔 管理

概念:

就一个类而言应该只有一个因其他变化的原因。

流程:

问题由来:设类或接口类C负责两个不同不同的职责:职责T1,职责T2。当由于职责T1需求改变进而需要修改类C时,可能导致职责T2收到不可预知的影响。

解决方案:分别建立两个类C1、C2,分管职责T1,T2。

优缺点:

1.优点: (1)、降低类的复杂度; (2)、 易维护、易扩展、可读性强 2.缺点: 使类或接口的数目增加, 难以控制。 示例代码 下面代码就没有遵循单一职责模式,如Operation即完成了+又完成了-。

package Pattern;

import java.util.Scanner;

class Operation {
    String operationName;

    public Operation(String tempOperationName) {
        operationName = tempOperationName;
    }

    public int GetResult(int opA, int opB) {

        if (operationName.equals("+"))
            return opA + opB;
        else
            return opA - opB;
    }
}

public class Pattern {
    public static void main(String[] args) {
        try {

            Scanner input = new Scanner(System.in);
            int opA, opB, result;
            opA = input.nextInt();
            opB = input.nextInt();

            Operation myOperation = new Operation("+");
            result = myOperation.GetResult(opA, opB);
            System.out.println(result);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

  尝试单一职责模式可以拆开

package Pattern;

import java.util.Scanner;

class AddOperation {
    public int GetResult(int opA, int opB) {
            return opA + opB;
    }
}

class SubOperation {
    public int GetResult(int opA, int opB) {
            return opA - opB;
    }
}

public class Pattern {
    public static void main(String[] args) {
        try {

            Scanner input = new Scanner(System.in);
            int opA, opB, result;
            
            opA = input.nextInt();
            opB = input.nextInt();
            AddOperation myAddOperation = new AddOperation();
            result = myAddOperation.GetResult(opA, opB);
            System.out.println(result);
            
            opA = input.nextInt();
            opB = input.nextInt();
            SubOperation mySubOperation = new SubOperation();
            result = mySubOperation.GetResult(opA, opB);
            System.out.println(result);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
posted on 2015-05-13 10:31  Sam Flynn  阅读(463)  评论(0编辑  收藏  举报