Program Tip

Java의 핵심 라이브러리에있는 GoF 디자인 패턴의 예

programtip 2020. 9. 30. 11:19
반응형

Java의 핵심 라이브러리에있는 GoF 디자인 패턴의 예


저는 GoF Java Design Patterns를 배우고 있으며 실제 사례를보고 싶습니다. Java의 핵심 라이브러리에서 이러한 디자인 패턴의 좋은 예는 무엇입니까?


Wikipedia 에서 많은 디자인 패턴에 대한 개요를 찾을 수 있습니다 . 또한 GoF에서 언급 한 패턴에 대해서도 언급합니다. 여기서 요약하고 Java SE 및 Java EE API 모두에서 찾을 수있는 가능한 한 많은 패턴 구현을 지정하려고합니다.


창조 패턴

추상 팩토리 (다른 추상 / 인터페이스 유형을 만드는 데 사용할 수있는 팩토리 자체를 반환하는 생성 방법으로 인식 가능)

작성기 (인스턴스 자체를 반환하는 생성 방법으로 인식 가능)

팩토리 메서드 (추상 / 인터페이스 유형의 구현을 반환하는 생성 메서드로 인식 가능)

프로토 타입 ( 동일한 속성을 가진 다른 인스턴스를 반환하는 생성 메서드로 인식 가능 )

Singleton ( 매번 동일한 인스턴스 (일반적으로 자체)를 반환하는 생성 메서드로 인식 가능 )


구조 패턴

어댑터 ( 다른 추상 / 인터페이스 유형 의 인스턴스를 취하고 주어진 인스턴스 장식 / 무시 하는 자체 / 다른 추상 / 인터페이스 유형의 구현을 반환하는 생성 방법으로 인식 가능 )

브리지 ( 다른 추상 / 인터페이스 유형 의 인스턴스를 취하고 주어진 인스턴스 위임 / 사용 하는 자체 추상 / 인터페이스 유형의 구현을 반환하는 생성 방법으로 인식 가능 )

  • 아직 떠오르는 사람이 없습니다. 가상의 예로들 수 new LinkedHashMap(LinkedHashSet<K>, List<V>)변경 불가능한 연결 항목을 복제하지 않는지도 만 돌려 사용 을. 그러나 java.util.Collections#newSetFromMap()singletonXXX()메서드는 가깝습니다.

Composite (recognizeable by behavioral methods taking an instance of same abstract/interface type into a tree structure)

Decorator (recognizeable by creational methods taking an instance of same abstract/interface type which adds additional behaviour)

Facade (recognizeable by behavioral methods which internally uses instances of different independent abstract/interface types)

Flyweight (recognizeable by creational methods returning a cached instance, a bit the "multiton" idea)

Proxy (recognizeable by creational methods which returns an implementation of given abstract/interface type which in turn delegates/uses a different implementation of given abstract/interface type)


Behavioral patterns

Chain of responsibility (recognizeable by behavioral methods which (indirectly) invokes the same method in another implementation of same abstract/interface type in a queue)

Command (recognizeable by behavioral methods in an abstract/interface type which invokes a method in an implementation of a different abstract/interface type which has been encapsulated by the command implementation during its creation)

Interpreter (recognizeable by behavioral methods returning a structurally different instance/type of the given instance/type; note that parsing/formatting is not part of the pattern, determining the pattern and how to apply it is)

Iterator (recognizeable by behavioral methods sequentially returning instances of a different type from a queue)

Mediator (recognizeable by behavioral methods taking an instance of different abstract/interface type (usually using the command pattern) which delegates/uses the given instance)

Memento (recognizeable by behavioral methods which internally changes the state of the whole instance)

Observer (or Publish/Subscribe) (recognizeable by behavioral methods which invokes a method on an instance of another abstract/interface type, depending on own state)

State (recognizeable by behavioral methods which changes its behaviour depending on the instance's state which can be controlled externally)

Strategy (recognizeable by behavioral methods in an abstract/interface type which invokes a method in an implementation of a different abstract/interface type which has been passed-in as method argument into the strategy implementation)

Template method (recognizeable by behavioral methods which already have a "default" behaviour defined by an abstract type)

Visitor (recognizeable by two different abstract/interface types which has methods defined which takes each the other abstract/interface type; the one actually calls the method of the other and the other executes the desired strategy on it)


  1. Observer pattern throughout whole swing (Observable, Observer)
  2. MVC also in swing
  3. Adapter pattern: InputStreamReader and OutputStreamWriter NOTE: ContainerAdapter, ComponentAdapter, FocusAdapter, KeyAdapter, MouseAdapter are not adapters; they are actually Null Objects. Poor naming choice by Sun.
  4. Decorator pattern (BufferedInputStream can decorate other streams such as FilterInputStream)
  5. AbstractFactory Pattern for the AWT Toolkit and the Swing pluggable look-and-feel classes
  6. java.lang.Runtime#getRuntime() is Singleton
  7. ButtonGroup for Mediator pattern
  8. Action, AbstractAction may be used for different visual representations to execute same code -> Command pattern
  9. Interned Strings or CellRender in JTable for Flyweight Pattern (Also think about various pools - Thread pools, connection pools, EJB object pools - Flyweight is really about management of shared resources)
  10. The Java 1.0 event model is an example of Chain of Responsibility, as are Servlet Filters.
  11. Iterator pattern in Collections Framework
  12. Nested containers in AWT/Swing use the Composite pattern
  13. Layout Managers in AWT/Swing are an example of Strategy

and many more I guess


  1. Flyweight is used with some values of Byte, Short, Integer, Long and String.
  2. Facade is used in many place but the most obvious is Scripting interfaces.
  3. Singleton - java.lang.Runtime comes to mind.
  4. Abstract Factory - Also Scripting and JDBC API.
  5. Command - TextComponent's Undo/Redo.
  6. Interpreter - RegEx (java.util.regex.) and SQL (java.sql.) API.
  7. Prototype - Not 100% sure if this count, but I thinkg clone() method can be used for this purpose.

RMI is based on Proxy.

Should be possible to cite one for most of the 23 patterns in GoF:

  1. Abstract Factory: java.sql interfaces all get their concrete implementations from JDBC JAR when driver is registered.
  2. Builder: java.lang.StringBuilder.
  3. Factory Method: XML factories, among others.
  4. Prototype: Maybe clone(), but I'm not sure I'm buying that.
  5. Singleton: java.lang.System
  6. Adapter: Adapter classes in java.awt.event, e.g., WindowAdapter.
  7. Bridge: Collection classes in java.util. List implemented by ArrayList.
  8. Composite: java.awt. java.awt.Component + java.awt.Container
  9. Decorator: All over the java.io package.
  10. Facade: ExternalContext behaves as a facade for performing cookie, session scope and similar operations.
  11. Flyweight: Integer, Character, etc.
  12. Proxy: java.rmi package
  13. Chain of Responsibility: Servlet filters
  14. Command: Swing menu items
  15. Interpreter: No directly in JDK, but JavaCC certainly uses this.
  16. Iterator: java.util.Iterator interface; can't be clearer than that.
  17. Mediator: JMS?
  18. Memento:
  19. Observer: java.util.Observer/Observable (badly done, though)
  20. State:
  21. Strategy:
  22. Template:
  23. Visitor:

I can't think of examples in Java for 10 out of the 23, but I'll see if I can do better tomorrow. That's what edit is for.


The Abstract Factory pattern is used in various places. E.g., DatagramSocketImplFactory, PreferencesFactory. There are many more---search the Javadoc for interfaces which have the word "Factory" in their name.

Also there are quite a few instances of the Factory pattern, too.


Even though I'm sort of a broken clock with this one, Java XML API uses Factory a lot. I mean just look at this:

Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(source);
String title = XPathFactory.newInstance().newXPath().evaluate("//title", doc);

...and so on and so forth.

Additionally various Buffers (StringBuffer, ByteBuffer, StringBuilder) use Builder.


java.util.Collection#Iterator is a good example of a Factory Method. Depending on the concrete subclass of Collection you use, it will create an Iterator implementation. Because both the Factory superclass (Collection) and the Iterator created are interfaces, it is sometimes confused with AbstractFactory. Most of the examples for AbstractFactory in the the accepted answer (BalusC) are examples of Factory, a simplified version of Factory Method, which is not part of the original GoF patterns. In Facory the Factory class hierarchy is collapsed and the factory uses other means to choose the product to be returned.

  • Abstract Factory

An abstract factory has multiple factory methods, each creating a different product. The products produced by one factory are intended to be used together (your printer and cartridges better be from the same (abstract) factory). As mentioned in answers above the families of AWT GUI components, differing from platform to platform, are an example of this (although its implementation differs from the structure described in Gof).

참고URL : https://stackoverflow.com/questions/1673841/examples-of-gof-design-patterns-in-javas-core-libraries

반응형