반응형
프로토 타입 패턴은 창조적 인 패턴 중 하나입니다.
프로토 타입 패턴은 더 나은 성능으로 복제 객체를 만드는 데 도움이됩니다.
프로토 타입 패턴에서 새 객체를 만드는 대신 기존 객체의 복제본이 반환됩니다.
새 객체를 만드는 데 드는 비용이 비싸고 리소스 집약적 인 경우 프로토 타입 디자인 패턴을 사용합니다.
예제
다음 코드는 프로토 타입 패턴을 사용하여 객체를 만드는 방법을 보여줍니다.
처음에 Cloneable 인터페이스를 구현하는 Shape 추상 클래스를 작성합니다.
abstract class Shape implements Cloneable { private String id; protected String type; abstract void draw(); public String getType(){ return type; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Object clone() { Object clone = null; try { clone = super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return clone; } }
그런 다음 Shape 클래스를 확장하는 세 개의 구체적인 클래스를 만듭니다.
class Rectangle extends Shape { public Rectangle(){ type = "Rectangle"; } @Override public void draw() { System.out.println("Inside Rectangle::draw() method."); } } class Square extends Shape { public Square(){ type = "Square"; } @Override public void draw() { System.out.println("Inside Square::draw() method."); } } class Circle extends Shape { public Circle(){ type = "Circle"; } @Override public void draw() { System.out.println("Inside Circle::draw() method."); } }
그런 다음 셰이프 프로토 타입을 반환하는 ShapeProtoType 클래스를 만듭니다.
class ShapeProtoType{ private static Hashtable<String, Shape> shapeMap = new Hashtable<String, Shape>(); public static Shape getShape(String shapeId) { Shape cachedShape = shapeMap.get(shapeId); return (Shape) cachedShape.clone(); } public static void loadCache() { Circle circle = new Circle(); circle.setId("1"); shapeMap.put(circle.getId(),circle); Square square = new Square(); square.setId("2"); shapeMap.put(square.getId(),square); Rectangle rectangle = new Rectangle(); rectangle.setId("3"); shapeMap.put(rectangle.getId(),rectangle); } } public class Main{ public static void main(String[] args) { ShapeProtoType.loadCache(); Shape clonedShape = (Shape) ShapeProtoType.getShape("1"); System.out.println("Shape : " + clonedShape.getType()); Shape clonedShape2 = (Shape) ShapeProtoType.getShape("2"); System.out.println("Shape : " + clonedShape2.getType()); Shape clonedShape3 = (Shape) ShapeProtoType.getShape("3"); System.out.println("Shape : " + clonedShape3.getType()); } }
위의 코드는 다음 결과를 생성합니다.
출력 결과
Shape : Circle
Shape : Square
Shape : Rectagle
반응형
'프로그래밍 > 자바 디자인 패턴' 카테고리의 다른 글
자바 디자인 패턴 튜토리얼 - 자바 디자인 패턴 - 싱글 톤 패턴 (0) | 2021.04.18 |
---|---|
자바 디자인 패턴 튜토리얼 - 자바 디자인 패턴 - 빌더 패턴 (0) | 2021.04.18 |
자바 디자인 패턴 튜토리얼 - 구조 설계 패턴 - 어댑터 패턴 (0) | 2021.04.18 |
자바 디자인 패턴 튜토리얼 - 구조 설계 패턴 - 브릿지 패턴 (0) | 2021.04.18 |
자바 디자인 패턴 튜토리얼 - 구조 설계 패턴 - 필터 / 기준 패턴 (0) | 2021.04.18 |