객체 생성 디자인 패턴이란?
객체를 생성하는 과정에서 효율성과 유지보수를 고려하여 구조화된 방법을 제공하는 패턴
클래스를 인스턴스화 할 때 직접 생성자를 호출하여 객체를 생성하는 가장 기본적인 패턴이다.
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void displayInfo() {
System.out.println("name: " + name + ", age: " + age);
}
public static void main(String[] args) {
Person person = new Person("홍길동", 25);
person.displayInfo();
}
}
클래스 내부에서 정적 메서드를 제공하여 객체를 생성하는 패턴이다.
public class Car {
private String model;
private Car(String model) {
this.model = model;
}
public static Car createCar(String model) {
return new Car(model);
}
public void showModel() {
System.out.println("model: " + model);
}
public static void main(String[] args) {
Car car = Car.createCar("Tesla");
car.showModel();
}
}
객체의 생성 과정을 단계별로 진행하고, 객체의 가독성을 높이는 패턴이다.
public class Computer {
private String CPU;
private String RAM;
private String storage;
private Computer(Builder builder) {
this.CPU = builder.CPU;
this.RAM = builder.RAM;
this.storage = builder.storage;
}
public static class Builder {
private String CPU;
private String RAM;
private String storage;
public Builder setCPU(String CPU) {
this.CPU = CPU;
return this;
}
public Builder setRAM(String RAM) {
this.RAM = RAM;
return this;
}
public Builder setStorage(String storage) {
this.storage = storage;
return this;
}
public Computer build() {
return new Computer(this);
}
}
public void showSpecs() {
System.out.println("CPU: " + CPU + ", RAM: " + RAM + ", storage: " + storage);
}
public static void main(String[] args) {
Computer computer = new Computer.Builder()
.setCPU("Intel i7")
.setRAM("16GB")
.setStorage("512GB SSD")
.build();
computer.showSpecs();
}
}
클래스의 인스턴스를 하나만 생성하고 이를 공유하는 패턴이다.
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
public void showMessage() {
System.out.println("싱글톤 객체입니다.");
}
public static void main(String[] args) {
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
singleton1.showMessage();
System.out.println(singleton1 == singleton2); // true
}
}
객체 생성을 서브 클래스에서 담당하도록 위임하는 패턴이다.
부모 클래스는 객체 생성 메서드를 제공하고, 자식 클래스는 실제 객체를 생성한다.
// 추상 Product 클래스
abstract class Product {
abstract void use();
}
// 구체적인 Product 클래스들
class ConcreteProductA extends Product {
@Override
void use() {
System.out.println("제품 A를 사용합니다.");
}
}
class ConcreteProductB extends Product {
@Override
void use() {
System.out.println("제품 B를 사용합니다.");
}
}
// 추상 Creator 클래스: 객체 생성 책임을 정의
abstract class Creator {
// 팩토리 메서드: 구체적인 객체 생성은 서브클래스에서 담당
abstract Product factoryMethod();
}
// 구체적인 Creator 클래스들
class ConcreteCreatorA extends Creator {
@Override
Product factoryMethod() {
return new ConcreteProductA();
}
}
class ConcreteCreatorB extends Creator {
@Override
Product factoryMethod() {
return new ConcreteProductB();
}
}
public class FactoryMethodExample {
public static void main(String[] args) {
Creator creatorA = new ConcreteCreatorA();
Product productA = creatorA.factoryMethod();
productA.use();
Creator creatorB = new ConcreteCreatorB();
Product productB = creatorB.factoryMethod();
productB.use();
}
}
서로 관련된 객체 군을 생성할 수 있도록 도와주는 패턴이다.
일관된 스타일이나 기능을 유지하며 함께 사용될 수 있도록 한 팩토리에서 생성하도록 한다.
// 추상 제품군
interface Chair {
void sit();
}
interface Sofa {
void lieDown();
}
// 구체적인 제품: 서로 다른 스타일의 의자 구현
class ModernChair implements Chair {
public void sit() {
System.out.println("현대적인 의자에 앉았습니다.");
}
}
class VictorianChair implements Chair {
public void sit() {
System.out.println("빅토리아 스타일 의자에 앉았습니다.");
}
}
// 구체적인 제품: 서로 다른 스타일의 소파 구현
class ModernSofa implements Sofa {
public void lieDown() {
System.out.println("현대적인 소파에 누웠습니다.");
}
}
class VictorianSofa implements Sofa {
public void lieDown() {
System.out.println("빅토리아 스타일 소파에 누웠습니다.");
}
}
// 추상 팩토리 : 관련된 제품군(의자, 소파)을 생성하는 메서드 선언
interface FurnitureFactory {
Chair createChair();
Sofa createSofa();
}
// 구체적인 팩토리: 제품군 전체를 생성하는 방법 구현
class ModernFurnitureFactory implements FurnitureFactory {
public Chair createChair() {
return new ModernChair();
}
public Sofa createSofa() {
return new ModernSofa();
}
}
class VictorianFurnitureFactory implements FurnitureFactory {
public Chair createChair() {
return new VictorianChair();
}
public Sofa createSofa() {
return new VictorianSofa();
}
}
public class AbstractFactoryExample {
public static void main(String[] args) {
// 현대 스타일 가구 공장 사용
FurnitureFactory modernFactory = new ModernFurnitureFactory();
Chair modernChair = modernFactory.createChair();
Sofa modernSofa = modernFactory.createSofa();
modernChair.sit();
modernSofa.lieDown();
// 빅토리아 스타일 가구 공장 사용
FurnitureFactory victorianFactory = new VictorianFurnitureFactory();
Chair victorianChair = victorianFactory.createChair();
Sofa victorianSofa = victorianFactory.createSofa();
victorianChair.sit();
victorianSofa.lieDown();
}
}
기존 객체를 복제(clone)하여 새로운 객체를 생성하는 패턴이다.
public class Prototype implements Cloneable {
private String data;
public Prototype(String data) {
this.data = data;
}
public void showData() {
System.out.println("Data: " + data);
}
@Override
protected Prototype clone() throws CloneNotSupportedException {
return (Prototype) super.clone();
}
public static void main(String[] args) throws CloneNotSupportedException {
Prototype original = new Prototype("Original");
Prototype clone = original.clone();
original.showData();
clone.showData();
}
}