Development Tip

전략 패턴과 명령 패턴의 차이점

yourdevel 2020. 12. 2. 22:04
반응형

전략 패턴과 명령 패턴의 차이점


전략 패턴명령 패턴 의 차이점은 무엇입니까 ? 또한 Java로 된 몇 가지 예를 찾고 있습니다.


일반적으로 명령 패턴은 수행해야하는 작업 에서 개체를 만드는 데 사용됩니다 . 작업 및 인수를 가져 와서 기록 할 개체에 래핑하고 실행 취소를 위해 보류하고 원격 사이트로 보내는 등의 작업을 수행합니다. 시간이 지남에 따라 시스템의 특정 지점을 통과하는 많은 수의 고유 한 Command 개체가되는 경향이 있으며 Command 개체는 요청 된 작업을 설명하는 다양한 매개 변수를 보유합니다.

반면에 전략 패턴은 어떤 작업을 수행해야 하는지를 지정 하는 데 사용되며 특정 알고리즘을 제공하기 위해 더 큰 개체 또는 메서드에 연결됩니다. 정렬 전략은 병합 정렬, 삽입 정렬 또는 목록이 최소 크기보다 큰 경우 병합 정렬을 사용하는 것과 같이 더 복잡한 것일 수 있습니다. 전략 개체는 Command 개체에 대한 대량 셔플 링을 거의받지 않고 대신 구성 또는 조정 목적으로 자주 사용됩니다.

두 패턴 모두 독립적 인 가변성을 제공하기 위해 코드를 포함하고있는 원래 클래스에서 개별 작업에 대한 매개 변수와 코드를 다른 개체에 인수 분해하는 작업을 포함합니다. 차이점은 실제로 발생하는 사용 사례와 각 패턴의 의도에 있습니다.


이미 단어가 주어졌습니다. 구체적인 코드의 차이점은 다음과 같습니다.

public class ConcreteStrategy implements BaseStrategy {

    @Override
    public void execute(Object argument) {
        // Work with passed-in argument.
    }

}

public class ConcreteCommand implements BaseCommand {

    private Object argument;

    public ConcreteCommand(Object argument) {
        this.argument = argument;
    }

    @Override
    public void execute() {
        // Work with own state.
    }

}

전략-Quicksort 또는 Mergesort [algo change]

Command-열기 또는 닫기 [동작 변경]


주요 차이점은 명령이 객체에 대해 몇 가지 작업을 수행한다는 것입니다. 개체의 상태를 변경할 수 있습니다.

전략은 객체를 처리하는 방법을 결정합니다. 일부 비즈니스 로직을 캡슐화합니다.


전략 패턴은 특정 기능에 대해 여러 구현 (알고리즘)이 있고 매개 변수 유형에 따라 런타임시 알고리즘을 변경하려는 경우에 유용합니다.

HttpServlet 코드의 좋은 예 :

service() 메소드는 메소드 유형에 따라 사용자의 요청을 doGet () 또는 doPost () 또는 다른 메소드로 안내합니다.

protected void service(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
    {
    String method = req.getMethod();

    if (method.equals(METHOD_GET)) {
        long lastModified = getLastModified(req);
        if (lastModified == -1) {
        // servlet doesn't support if-modified-since, no reason
        // to go through further expensive logic
        doGet(req, resp);
        } else {
        long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
        if (ifModifiedSince < (lastModified / 1000 * 1000)) {
            // If the servlet mod time is later, call doGet()
                    // Round down to the nearest second for a proper compare
                    // A ifModifiedSince of -1 will always be less
            maybeSetLastModified(resp, lastModified);
            doGet(req, resp);
        } else {
            resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        }
        }

    } else if (method.equals(METHOD_HEAD)) {
        long lastModified = getLastModified(req);
        maybeSetLastModified(resp, lastModified);
        doHead(req, resp);

    } else if (method.equals(METHOD_POST)) {
        doPost(req, resp);

    } else if (method.equals(METHOD_PUT)) {
        doPut(req, resp);   

    } else if (method.equals(METHOD_DELETE)) {
        doDelete(req, resp);

    } else if (method.equals(METHOD_OPTIONS)) {
        doOptions(req,resp);

    } else if (method.equals(METHOD_TRACE)) {
        doTrace(req,resp);

    } else {
        //
        // Note that this means NO servlet supports whatever
        // method was requested, anywhere on this server.
        //

        String errMsg = lStrings.getString("http.method_not_implemented");
        Object[] errArgs = new Object[1];
        errArgs[0] = method;
        errMsg = MessageFormat.format(errMsg, errArgs);

        resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
    }
    }

전략 패턴의 두드러진 특징

  1. 행동 패턴입니다
  2. 위임을 기반으로 함
  3. It changes guts of the object by modifying method behaviour
  4. It's used to switch between family of algorithms
  5. It changes the behaviour of the object at run time

Command pattern is used to enable loose coupling between Invoker and Receiver. Command, ConcreteCommand, Receiver, Invoker and Client are major components of this pattern.

Different Receivers will execute same Command through Invoker & Concrete Command but the implementation of Command will vary in each Receiver.

e.g. You have to implement "On" and "Off" functionality for TV & DVDPlayer. But TV and DVDPlayer will have different implementation for these commands.

Have a look at below posts with code examples :

Real World Example of the Strategy Pattern

Using Command Design pattern

참고URL : https://stackoverflow.com/questions/4834979/difference-between-strategy-pattern-and-command-pattern

반응형