IT TIP

복합 디자인 패턴은 언제 사용해야합니까?

itqueen 2020. 12. 10. 21:36
반응형

복합 디자인 패턴은 언제 사용해야합니까?


이해가 안 나는 복합 디자인 패턴을 사용해야 할 때 . 이 디자인 패턴에서 어떤 이점을 얻을 수 있습니까? 이 웹 사이트를 방문 했지만 디자인 패턴의 구조에 대해서만 알려주고 사용 시나리오는 알려주지 않습니다. 디자인 패턴을 배우기 시작한 저와 같은 프로그래머에게 도움이 되길 바랍니다.


디자인 패턴 에서 인용 ,

다음과 같은 경우 복합 패턴을 사용합니다.

  • 개체의 부분 전체 계층을 나타내려고합니다.
  • 클라이언트가 개체 구성과 개별 개체 간의 차이를 무시할 수 있기를 원합니다. 클라이언트는 복합 구조의 모든 개체를 균일하게 취급합니다.

일반적인 용법은 이미지, 텍스트와 같은 그래픽 요소와 다른 창을 포함 할 수있는 그래픽 창의 디스플레이 시스템 인 책에서 동기를 부여하는 예로 사용되는 것입니다. 컴포지트는 런타임에 구성 할 수 있으며 클라이언트 코드는 그리기와 같은 일반적인 작업을위한 유형에 관계없이 모든 요소를 ​​조작 할 수 있습니다.


컴포지트는 계층 구조의 일부인 개체 그룹이 실제로 다를 때 "동일한"것으로 선택적으로 처리해야 할 때마다 유용한 패턴입니다. 일반적으로 사용 된 예제는 잎과 노드를 동일하게 처리하는 측면에서 말하지만 패턴은 이기종 목록으로 확장 될 수도 있습니다.

예를 들어, 의사 방문을 고려하십시오. 의사에게 가면 여러 가지 일이 일어나면 보통 간호사 나 조수를 먼저 만나고 체온을 측정합니다. 그런 다음 의사가 검사를하고 진단을 내립니다. 그런 다음 의사가 치료를 할 수 있지만 종종 간호사가 돌아와 마무리합니다. 그리고 방문하는 동안 다양한 활동이 수행됩니다. 체중 및 온도와 같은 관찰이 있습니다. 그러나 예를 들어 실험실은 종종 샘플이 필요하기 때문에 다른 개체가 될 것입니다. 샘플을 보내야하고 나중에 결과를 기록해야합니다.

따라서이 모든 것을 기록 할 수있는 소프트웨어가 있으며 일반적으로 다음과 같은 노드로 일종의 계층 구조를 생성합니다.

만남 : 시험

시험
치료

각 노드 아래에는 진단, 관찰, 실험실 절차, 진단, 주입 등과 같은 다양한 항목이 있습니다.

이것은 모두 훌륭하고 훌륭하며, 구조화 된, 비록 매우 복잡한 만남의 계층 적 기록으로 끝납니다.

이제 청구를 생성해야한다고 가정합니다. 갑자기 당신은 매우 다른 요구 사항에 직면하게됩니다. 만남의 매우 정확한 그림을 만들기 위해 의료 기록이 필요했습니다. 청구에서 누가 무엇을 또는 ​​어떤 순서로했는지는 신경 쓰지 않지만 실제로 청구 코드를 넘어서는 활동이 무엇인지는 신경 쓰지 않습니다. 청구 가능한 활동 (예 : 코드)의 단일 목록을 원할뿐입니다.

이 정보는 레코드에 포함되어있을뿐만 아니라 많은 수의 다른 개체를 포함하기 때문에 해당 레코드를 탐색하기가 매우 어렵습니다. 또한 계층 적 구조에서도 다양합니다. 머리에 못이있는 경우 사전 검사 나 해당 문제에 대한 검사를 건너 뛰고 치료를받을 수 있습니다. 실밥을 제거하기 위해 들어가면 사전 시험이나 시험이 없을 수 있습니다. 연간 신체 검사에는 치료가 없습니다. 등등 등등. 이런 종류의 객체 그래프를 열거하는 것은 매우 어렵습니다.

복합 패턴은이 모든 것을 해결합니다. 모든 개체에 대해 공통 인터페이스 또는 기본 클래스를 정의합니다. "CareEntry"라고 부르겠습니다. CareEntry에는 BillingCode 속성이 있습니다. 이제 Encounter는 CareEntry 개체 만 포함 된 간단한 컨테이너처럼 보일 수 있습니다. 청구 서비스는 이제 노드 (PreExam, Exam) 대 잎 (무게 온도) 또는 개체가있는 노드 (PreExam Exam 등) 또는 실제 유형에 대해 걱정할 필요없이 내부의 모든 것을 간단히 열거 할 수 있습니다. 개체의 (실험실, 주입 등)입니다. 모든 것이 CareEntry이며 균일하게 처리됩니다. Encounter에서 모든 CareEntry 개체를 열거하고 널이 아닌 청구 코드가있는 각 개체를 수집하면됩니다. 그렇게 간단합니다.


컴포지트 패턴을 사용하면 클라이언트가 개별 오브젝트와 컴포지션 (개별 오브젝트)을 균일하게 처리 할 수 ​​있습니다.
예를 들어 폴더를 두 번 클릭하면 폴더가 열립니다. 파일의 두 배에 해당하는 프로그램에서 열어야합니다.
작업은 동일하지만 개별 개체인지 컴포지션인지에 따라 작동합니다.

개별 개체 및 복합 개체에 대한 공통 인터페이스

interface Data{
    public void doubleClick();
}

개별 개체 구현

class File implements Data {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public void doubleClick() {
        System.out.println(this.getName()+" file is Opened in a Program ");
    }
}

복합 구현

class Folder implements Data {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    private List<Data> folder = new ArrayList<Data>();

    @Override
    public void doubleClick() {
        System.out.println(this.getName() + " folder is Opened");
        for(Data data : folder) {
            data.doubleClick();
        }
    }

    public void add(Data data) {
        folder.add(data);
    }

    public void remove(Data data) {
        folder.remove(data);
    }
}

클라이언트 프로그램

public class CompositePattern {

    public static void main(String[] args) {

        Folder f1 = new Folder();f1.setName("Folder 1");
        Folder f2 = new Folder();f2.setName("Folder 2");
        Folder f3 = new Folder();f3.setName("Folder 3");

        File file1 = new File();file1.setName("File 1");
        File file2 = new File();file2.setName("File 2");
        File file3 = new File();file3.setName("File 3");
        File file4 = new File();file4.setName("File 4");

        f1.add(file1);
        f2.add(file2);

        f3.add(f2);
        f3.add(file3);
        f3.add(file4);

        f1.doubleClick();f2.doubleClick();f3.doubleClick();

    }

}

나는 종종 복합 디자인 패턴을 사용하여 컬렉션을 숨 깁니다. 많은 경우에 우리는 많은 요소가 있고 하나의 요소 만있을 때 똑같은 방식으로 컬렉션을 사용합니다.

That is the problem, because the class containing a collection then swarms with foreach loops that basically do the same thing - walk through all elements and apply some aggregate function.

To resolve the issue, I introduce an interface which is implemented by the single element as well as the class hiding the collection of those elements. The purpose of the composite class is then to contain all the aggregate functions that used to be in the client class.

You can find some useful examples in this article: Working With Collections

Common thing here is that Composite is not necessarily representing the part-whole relationship. It is possible to introduce composite element just to move the loops out of the client.

And here is one by-the-book example of applying the Composite pattern to hide parts behind the composite element: Composite Design Pattern


Having recently studied and tried my hand at it, I recognized one powerful concept to keep in mind about Composites.

Composites hide the complexity involved in the collections, i.e. looping through them, sorting them out, filtering some etc. and allows you to treat it as if it is a single organism.

Say, you have a dog at one kennel and many dogs at another. You want to feed them and vaccinate them but you cannot feed them if they ate within an hour or feed them if they were vaccinated in the last five hours, or vaccinate them if they vomited etc.

More importantly, there are rules of packing order where dog breed A eats before breed B, unless breed C dog was around and barking to the top of his lungs.

This will quickly reach to a point where you simply don't want to care about anything but just call a helper and tell him to feed 'all dogs'. Or better, three helpers to keep track of feeding, vaccination and vomiting, barking and packing and all other awesome stuff.

By calling out helpers, you relied on the Composition pattern. You just go and 'feed' each kennel, be it one dog or a ten. You just want the kennel full of dogs to sort it out themselves and figure out how they feed, because you have too much in your hands at the cashier.

So, for you, a Dog is an IDog, who Feed(), Bark(), Vomit() and GetVaccine(). A Kennel is also a Dog, who you call kennel.Feed(). You are done. The Kennel kennel has to figure out what to do now internally. It may have a time keeping mechanism to follow each dog's feeding and other bodily function times. It is all encapsulated neatly.


You may find it being-a-must when you will be working with binary trees or other complex data structures like list of lists of lists - etc... then, when every element (class) implements 1 interface, you can do the same methods on 1 leaf or on whole group of them - copping, adding, removing, moving... whatever, what you have implemented correctly. It's very useful and simple.


The answer should be -

Compose objects into tree structures to represent whole-part hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

  • Recursive composition
  • “Directories contain entries, each of which could be a directory.”
  • 1-to-many “has a” up the “is a” hierarchy

copied from a forum.


Composite design pattern real world example, When we have chances of having instance of same parent type inside or component type.

Example: In foreign exchange trading systems Ex1

You might have a cross currency pair (AUD/EUR)= (AUD/USD and 1/(EUR/USD)) the point here is your Instrument(Cross) can have two Instruments(Direct) inside.

In another example have

One Instrument(Cross) and Instrument(Direct) and Instrument(Cross) which can be further divided in to tow Instrument(Direct). SGD/CZK = USD/SGD (Direct) and USD/CZK (Cross) = USD/SGD (Direct) and (1/EUR/USD)(Direct) and EUR/CZK(Direct)

The point here is you keep dividing until you don't find all direct currency pairs.

Above can be easily implemented using Composite Design pattern.


Hope this simple example helps


if you want to build nested similar object means you can go for composite design pattern eg: in realtime if you want to show tree structure for the office employee based on hierarchy

참고URL : https://stackoverflow.com/questions/5334353/when-should-i-use-composite-design-pattern

반응형