여러분, 안녕하세요. 이전 기사 에서 각 패턴에 대해 간략하게 설명했습니다. 이 기사에서는 패턴을 사용하는 방법을 자세히 보여주려고 합니다.
창작
하나씩 일어나는 것
설명: 클래스 생성을 단일 인스턴스로 제한하고 해당 단일 인스턴스에 대한 액세스를 제공합니다. 클래스의 생성자는 비공개입니다. 이getInstance()
메서드는 클래스의 인스턴스를 하나만 만듭니다. 구현:
class Singleton {
private static Singleton instance = null;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
public void setUp() {
System.out.println("setUp");
}
}
public class SingletonTest { // Test
public static void main(String[] args){
Singleton singelton = Singleton.getInstance();
singelton.setUp();
}
}
공장
설명: 여러 하위 클래스가 있는 상위 클래스가 있고 입력을 기반으로 하위 클래스를 반환해야 할 때 사용됩니다. 클래스는 생성해야 하는 개체의 유형을 모릅니다. 개체는 입력을 기반으로 생성됩니다. 구현:
class Factory {
public OS getCurrentOS(String inputOS) {
OS os = null;
if (inputOS.equals("windows")) {
os = new windowsOS();
} else if (inputOS.equals("linux")) {
os = new linuxOS();
} else if (inputOS.equals("mac")) {
os = new macOS();
}
return os;
}
}
interface OS {
void getOS();
}
class windowsOS implements OS {
public void getOS () {
System.out.println("uses Windows");
}
}
class linuxOS implements OS {
public void getOS () {
System.out.println("uses Linux");
}
}
class macOS implements OS {
public void getOS () {
System.out.println("uses macOS");
}
}
public class FactoryTest { // Test
public static void main(String[] args){
String osName = "linux";
Factory factory = new Factory();
OS os = factory.getCurrentOS(osName);
os.getOS();
}
}
추상 공장
설명: 가능한 팩토리 제품군에서 특정 팩토리 구현을 선택할 수 있습니다. 관련 개체의 패밀리를 만듭니다. 확장하기 쉽습니다. 구현:
interface Lada {
long getLadaPrice();
}
interface Ferrari {
long getFerrariPrice();
}
interface Porshe {
long getPorshePrice();
}
interface InteAbsFactory {
Lada getLada();
Ferrari getFerrari();
Porshe getPorshe();
}
class UaLadaImpl implements Lada { // First
public long getLadaPrice() {
return 1000;
}
}
class UaFerrariImpl implements Ferrari {
public long getFerrariPrice() {
return 3000;
}
}
class UaPorsheImpl implements Porshe {
public long getPorshePrice() {
return 2000;
}
}
class UaCarPriceAbsFactory implements InteAbsFactory {
public Lada getLada() {
return new UaLadaImpl();
}
public Ferrari getFerrari() {
return new UaFerrariImpl();
}
public Porshe getPorshe() {
return new UaPorsheImpl();
}
} // First
class RuLadaImpl implements Lada { // Second
public long getLadaPrice() {
return 10000;
}
}
class RuFerrariImpl implements Ferrari {
public long getFerrariPrice() {
return 30000;
}
}
class RuPorsheImpl implements Porshe {
public long getPorshePrice() {
return 20000;
}
}
class RuCarPriceAbsFactory implements InteAbsFactory {
public Lada getLada() {
return new RuLadaImpl();
}
public Ferrari getFerrari() {
return new RuFerrariImpl();
}
public Porshe getPorshe() {
return new RuPorsheImpl();
}
} // Second
public class AbstractFactoryTest { // Test
public static void main(String[] args) {
String country = "UA";
InteAbsFactory ifactory = null;
if(country.equals("UA")) {
ifactory = new UaCarPriceAbsFactory();
} else if(country.equals("RU")) {
ifactory = new RuCarPriceAbsFactory();
}
Lada lada = ifactory.getLada();
System.out.println(lada.getLadaPrice());
}
}
빌더
설명: 단순 개체를 사용하여 복합 개체를 생성하는 데 사용됩니다. 작고 단순한 개체에서 점차 큰 개체를 만듭니다. 최종 제품의 내부 표현을 변경할 수 있습니다. 구현:
class Car {
public void buildBase() {
print("Building the base");
}
public void buildWheels() {
print("Installing wheels");
}
public void buildEngine(Engine engine) {
print("Installing engine: " + engine.getEngineType());
}
private void print(String msg){
System.out.println(msg);
}
}
interface Engine {
String getEngineType();
}
class EngineOne implements Engine {
public String getEngineType() {
return "First engine";
}
}
class EngineTwo implements Engine {
public String getEngineType() {
return "Second engine";
}
}
abstract class Builder {
protected Car car;
public abstract Car buildCar();
}
class OneBuilderImpl extends Builder {
public OneBuilderImpl(){
car = new Car();
}
public Car buildCar() {
car.buildBase();
car.buildWheels();
Engine engine = new EngineOne();
car.buildEngine(engine);
return car;
}
}
class TwoBuilderImpl extends Builder {
public TwoBuilderImpl(){
car = new Car();
}
public Car buildCar() {
car.buildBase();
car.buildWheels();
Engine engine = new EngineOne();
car.buildEngine(engine);
car.buildWheels();
engine = new EngineTwo();
car.buildEngine(engine);
return car;
}
}
class Build {
private Builder builder;
public Build(int i){
if(i == 1) {
builder = new OneBuilderImpl();
} else if(i == 2) {
builder = new TwoBuilderImpl();
}
}
public Car buildCar(){
return builder.buildCar();
}
}
public class BuilderTest { // Test
public static void main(String[] args) {
Build build = new Build(1);
build.buildCar();
}
}
원기
설명: 복제 개체를 생성할 때 성능을 향상시키는 데 도움이 됩니다. 새 개체를 만드는 대신 기존 개체의 복제본을 만들어 반환합니다. 기존 개체를 복제합니다. 구현:
interface Copyable {
Copyable copy();
}
class ComplicatedObject implements Copyable {
private Type type;
public enum Type {
ONE, TWO
}
public ComplicatedObject copy() {
ComplicatedObject complicatedObject = new ComplicatedObject();
return complicatedObject;
}
public void setType(Type type) {
this.type = type;
}
}
public class PrototypeTest { // Test
public static void main(String[] args) {
ComplicatedObject prototype = new ComplicatedObject();
ComplicatedObject clone = prototype.copy();
clone.setType(ComplicatedObject.Type.ONE);
}
}
구조적
어댑터
설명: 어댑터 패턴을 사용하여 호환되지 않는 두 인터페이스를 결합할 수 있습니다. 호환되지 않는 두 개체 간의 변환기 역할을 합니다. 구현:
class PBank {
private int balance;
public PBank() { balance = 100; }
public void getBalance() {
System.out.println("PBank balance = " + balance);
}
}
class ABank {
private int balance;
public ABank() { balance = 200; }
public void getBalance() {
System.out.println("ABank balance = " + balance);
}
}
class PBankAdapter extends PBank {
private ABank abank;
public PBankAdapter(ABank abank) {
this.abank = abank;
}
public void getBalance() {
abank.getBalance();
}
}
public class AdapterTest { // Test
public static void main(String[] args) {
PBank pbank = new PBank();
pbank.getBalance();
PBankAdapter abank = new PBankAdapter(new ABank());
abank.getBalance();
}
}
합성물
설명: 하나의 클래스를 사용하여 여러 개체를 트리 구조로 그룹화합니다. 단일 개체를 통해 여러 클래스로 작업할 수 있습니다. 구현:
import java.util.ArrayList;
import java.util.List;
interface Car {
void draw(String color);
}
class SportsCar implements Car {
public void draw(String color) {
System.out.println("SportsCar color: " + color);
}
}
class UnknownCar implements Car {
public void draw(String color) {
System.out.println("UnknownCar color: " + color);
}
}
class Drawing implements Car {
private List<Car> cars = new ArrayList<Car>();
public void draw(String color) {
for(Car car : cars) {
car.draw(color);
}
}
public void add(Car s){
this.cars.add(s);
}
public void clear(){
System.out.println();
this.cars.clear();
}
}
public class CompositeTest { // Test
public static void main(String[] args) {
Car sportsCar = new SportsCar();
Car unknownCar = new UnknownCar();
Drawing drawing = new Drawing();
drawing.add(sportsCar);
drawing.add(unknownCar);
drawing.draw("green");
drawing.clear();
drawing.add(sportsCar);
drawing.add(unknownCar);
drawing.draw("white");
}
}
대리
설명: 메서드 호출을 가로채 다른 개체를 제어할 수 있는 개체를 나타냅니다. 원래 개체의 메서드 호출을 가로챌 수 있습니다. 구현:
interface Image {
void display();
}
class RealImage implements Image {
private String file;
public RealImage(String file){
this.file = file;
load(file);
}
private void load(String file){
System.out.println("Loading " + file);
}
public void display() {
System.out.println("Displaying " + file);
}
}
class ProxyImage implements Image {
private String file;
private RealImage image;
public ProxyImage(String file){
this.file = file;
}
public void display() {
if(image == null){
image = new RealImage(file);
}
image.display();
}
}
public class ProxyTest { // Test
public static void main(String[] args) {
Image image = new ProxyImage("test.jpg");
image.display();
image.display();
}
}
플라이급
설명: 유사한 개체를 많이 만드는 대신 개체를 재사용합니다. 메모리를 절약합니다. 구현:
class Flyweight {
private int row;
public Flyweight(int row) {
this.row = row;
System.out.println("ctor: " + this.row);
}
void report(int col) {
System.out.print(" " + row + col);
}
}
class Factory {
private Flyweight[] pool;
public Factory(int maxRows) {
pool = new Flyweight[maxRows];
}
public Flyweight getFlyweight(int row) {
if (pool[row] == null) {
pool[row] = new Flyweight(row);
}
return pool[row];
}
}
public class FlyweightTest { // Test
public static void main(String[] args) {
int rows = 5;
Factory theFactory = new Factory(rows);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < rows; j++) {
theFactory.getFlyweight(i).report(j);
}
System.out.println();
}
}
}
정면
설명: 모든 호출을 하나의 개체에 추가하여 복잡한 클래스 시스템을 숨깁니다. 여러 복합 개체의 메서드 호출을 단일 개체에 배치합니다. 구현:
interface Car {
void start();
void stop();
}
class Key implements Car {
public void start() {
System.out.println("Insert keys");
}
public void stop() {
System.out.println("Remove keys");
}
}
class Engine implements Car {
public void start() {
System.out.println("Start engine");
}
public void stop() {
System.out.println ("Stop engine");
}
}
class Facade {
private Key key;
private Engine engine;
public Facade() {
key = new Key();
engine = new Engine();
}
public void startCar() {
key.start();
engine.start();
}
public void stoptCar() {
key.stop();
engine.stop();
}
}
public class FacadeTest { // Test
public static void main(String[] args) {
Facade facade = new Facade();
facade.startCar();
System.out.println();
facade.stoptCar();
}
}
다리
설명: 추상화에서 구현을 분리하여 서로 독립적으로 변경할 수 있습니다. 인터페이스를 구현하는 클래스와 독립적인 특정 클래스를 만듭니다. 구현:
interface Engine {
void setEngine();
}
abstract class Car {
protected Engine engine;
public Car(Engine engine){
this.engine = engine;
}
abstract public void setEngine();
}
class SportsCar extends Car {
public SportsCar(Engine engine) {
super(engine);
}
public void setEngine() {
System.out.print("SportsCar engine: ");
engine.setEngine();
}
}
class UnknownCar extends Car {
public UnknownCar(Engine engine) {
super(engine);
}
public void setEngine() {
System.out.print("UnknownCar engine: ");
engine.setEngine();
}
}
class PerformanceEngine implements Engine {
public void setEngine(){
System.out.println("sport");
}
}
class UnknownEngine implements Engine {
public void setEngine(){
System.out.println("unknown");
}
}
public class BridgeTest { // Test
public static void main(String[] args) {
Car sportsCar = new SportsCar(new PerformanceEngine());
sportsCar.setEngine();
System.out.println();
Car unknownCar = new UnknownCar(new UnknownEngine());
unknownCar.setEngine();
}
}
데코레이터
설명: 구조에 묶이지 않고 기존 개체에 새 기능을 추가합니다. 구현:
interface Car {
void draw();
}
class SportsCar implements Car {
public void draw() {
System.out.println("SportsCar");
}
}
class UnknownCar implements Car {
public void draw() {
System.out.println("UnknownCar");
}
}
abstract class CarDecorator implements Car {
protected Car decorated;
public CarDecorator(Car decorated){
this.decorated = decorated;
}
public void draw(){
decorated.draw();
}
}
class BlueCarDecorator extends CarDecorator {
public BlueCarDecorator(Car decorated) {
super(decorated);
}
public void draw() {
decorated.draw();
setColor();
}
private void setColor(){
System.out.println("Color: red");
}
}
public class DecoratorTest { // Test
public static void main(String[] args) {
Car sportsCar = new SportsCar();
Car blueUnknownCar = new BlueCarDecorator(new UnknownCar());
sportsCar.draw();
System.out.println();
blueUnknownCar.draw();
}
}
행동
템플릿 방법
설명: 기본 알고리즘을 정의할 수 있으며 자손이 전체 구조를 변경하지 않고 알고리즘의 일부 단계를 재정의할 수 있습니다. 구현:
abstract class Car {
abstract void startEngine();
abstract void stopEngine();
public final void start(){
startEngine();
stopEngine();
}
}
class CarOne extends Car {
public void startEngine() {
System.out.println("Start engine.");
}
public void stopEngine() {
System.out.println("Stop engine.");
}
}
class CarTwo extends Car {
public void startEngine() {
System.out.println("Start engine.");
}
public void stopEngine() {
System.out.println("Stop engine.");
}
}
public class TemplateTest { // Test
public static void main(String[] args) {
Car car1 = new CarOne();
car1.start();
System.out.println();
Car car2 = new CarTwo();
car2.start();
}
}
중재인
설명: 서로 다른 클래스 간의 모든 통신을 처리하는 중간 클래스를 제공합니다. 구현:
class Mediator {
public static void sendMessage(User user, String msg){
System.out.println(user.getName() + ": " + msg);
}
}
class User {
private String name;
public User(String name){
this.name = name;
}
public String getName() {
return name;
}
public void sendMessage(String msg){
Mediator.sendMessage(this, msg);
}
}
public class MediatorTest { // Test
public static void main(String[] args) {
User user1 = new User("user1");
User user2 = new User("user2");
user1.sendMessage("message1");
user2.sendMessage("message2");
}
}
책임의 사슬
설명: 요청 발신자와 수신자 간의 엄격한 의존성을 피할 수 있습니다. 또한 여러 개체에서 요청을 처리할 수 있습니다. 구현:
interface Payment {
void setNext(Payment payment);
void pay();
}
class VisaPayment implements Payment {
private Payment payment;
public void setNext(Payment payment) {
this.payment = payment;
}
public void pay() {
System.out.println("Visa Payment");
}
}
class PayPalPayment implements Payment {
private Payment payment;
public void setNext(Payment payment) {
this.payment = payment;
}
public void pay() {
System.out.println("PayPal Payment");
}
}
public class ChainofResponsibilityTest { // Test
public static void main(String[] args) {
Payment visaPayment = new VisaPayment();
Payment payPalPayment = new PayPalPayment();
visaPayment.setNext(payPalPayment);
visaPayment.pay();
}
}
관찰자
설명: 한 개체가 다른 개체에서 일어나는 일을 관찰할 수 있습니다. 구현:
import java.util.ArrayList;
import java.util.List;
interface Observer {
void event(List<String> strings);
}
class University {
private List<Observer> observers = new ArrayList<Observer>();
private List<String> students = new ArrayList<String>();
public void addStudent(String name) {
students.add(name);
notifyObservers();
}
public void removeStudent(String name) {
students.remove(name);
notifyObservers();
}
public void addObserver(Observer observer){
observers.add(observer);
}
public void removeObserver(Observer observer) {
observers.remove(observer);
}
public void notifyObservers(){
for (Observer observer : observers) {
observer.event(students);
}
}
}
class Director implements Observer {
public void event(List<String> strings) {
System.out.println("The list of students has changed: " + strings);
}
}
public class ObserverTest { // Test
public static void main(String[] args) {
University university = new University();
Director director = new Director();
university.addStudent("Oscar");
university.addObserver(director);
university.addStudent("Anna");
university.removeStudent("Oscar");
}
}
전략
설명: 일련의 알고리즘을 정의하고 상호 작용할 수 있도록 합니다. 런타임에 전략(알고리즘)을 변경할 수 있습니다. 구현:
interface Strategy {
void download(String file);
}
class WindowsDownloadStrategy implements Strategy {
public void download(String file) {
System.out.println("windows download: " + file);
}
}
class LinuxDownloadStrategy implements Strategy {
public void download(String file) {
System.out.println("linux download: " + file);
}
}
class Context {
private Strategy strategy;
public Context(Strategy strategy){
this.strategy = strategy;
}
public void download(String file){
strategy.download(file);
}
}
public class StrategyTest { // Test
public static void main(String[] args) {
Context context = new Context(new WindowsDownloadStrategy());
context.download("file.txt");
context = new Context(new LinuxDownloadStrategy());
context.download("file.txt");
}
}
명령
설명: 개별 개체에 다양한 작업을 캡슐화할 수 있습니다. 구현:
interface Command {
void execute();
}
class Car {
public void startEngine() {
System.out.println("Start engine");
}
public void stopEngine() {
System.out.println ("Stop engine");
}
}
class StartCar implements Command {
Car car;
public StartCar(Car car) {
this.car = car;
}
public void execute() {
car.startEngine();
}
}
class StopCar implements Command {
Car car;
public StopCar(Car car) {
this.car = car;
}
public void execute() {
car.stopEngine();
}
}
class CarInvoker {
public Command command;
public CarInvoker(Command command){
this.command = command;
}
public void execute(){
this.command.execute();
}
}
public class CommandTest { // Test
public static void main(String[] args) {
Car car = new Car();
StartCar startCar = new StartCar(car);
StopCar stopCar = new StopCar(car);
CarInvoker carInvoker = new CarInvoker(startCar);
carInvoker.execute();
}
}
상태
설명: 개체가 상태에 따라 동작을 변경할 수 있습니다. 구현:
interface State {
void doAction();
}
class StartPlay implements State {
public void doAction() {
System.out.println("start play");
}
}
class StopPlay implements State {
public void doAction() {
System.out.println("stop play");
}
}
class PlayContext implements State {
private State state;
public void setState(State state){
this.state = state;
}
public void doAction() {
this.state.doAction();
}
}
public class StateTest { // Test
public static void main(String[] args) {
PlayContext playContext = new PlayContext();
State startPlay = new StartPlay();
State stopPlay = new StopPlay();
playContext.setState(startPlay);
playContext.doAction();
playContext.setState(stopPlay);
playContext.doAction();
}
}
방문객
설명: 관련 개체 그룹에 대한 작업을 단순화하는 데 사용됩니다. 구현:
interface Visitor {
void visit(SportsCar sportsCar);
void visit(Engine engine);
void visit(Wheel wheel);
}
interface Car {
void accept(Visitor visitor);
}
class Engine implements Car {
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
class Wheel implements Car {
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
class SportsCar implements Car {
Car[] cars;
public SportsCar(){
cars = new Car[]{new Engine(), new Wheel()};
}
public void accept(Visitor visitor) {
for (int i = 0; i < cars.length; i++) {
cars[i].accept(visitor);
}
visitor.visit(this);
}
}
class CarVisitor implements Visitor {
public void visit(SportsCar computer) {
print("car");
}
public void visit(Engine engine) {
print("engine");
}
public void visit(Wheel wheel) {
print("wheel");
}
private void print(String string) {
System.out.println(string);
}
}
public class VisitorTest { // Test
public static void main(String[] args) {
Car computer = new SportsCar();
computer.accept(new CarVisitor());
}
}
통역사
설명: 문제 도메인에서 간단한 언어의 문법을 정의할 수 있습니다. 구현:
interface Expression {
String interpret(Context context);
}
class Context {
public String getLowerCase(String s){
return s.toLowerCase();
}
public String getUpperCase(String s){
return s.toUpperCase();
}
}
class LowerExpression implements Expression {
private String s;
public LowerExpression(String s) {
this.s = s;
}
public String interpret(Context context) {
return context.getLowerCase(s);
}
}
class UpperExpression implements Expression {
private String s;
public UpperExpression(String s) {
this.s = s;
}
public String interpret(Context context) {
return context.getUpperCase(s);
}
}
public class InterpreterTest { // Test
public static void main(String[] args) {
String str = "TesT";
Context context = new Context();
Expression lowerExpression = new LowerExpression(str);
str = lowerExpression.interpret(context);
System.out.println(str);
Expression upperExpression = new UpperExpression(str);
str = upperExpression.interpret(context);
System.out.println(str);
}
}
반복자
설명: 반복자는 기본 양식을 모른 채 컬렉션의 요소에 순차적으로 액세스합니다. 구현:
interface Iterator {
boolean hasNext();
Object next();
}
class Numbers {
public int num[] = {1 , 2, 3};
public Iterator getIterator() {
return new NumbersIterator();
}
private class NumbersIterator implements Iterator {
int ind;
public boolean hasNext() {
if(ind < num.length) return true;
return false;
}
public Object next() {
if(this.hasNext()) return num[ind++];
return null;
}
}
}
public class IteratorTest { // Test
public static void main(String[] args) {
Numbers numbers = new Numbers();
Iterator iterator = numbers.getIterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
기념물
설명: 개체의 현재 상태를 저장할 수 있습니다. 이 상태는 나중에 복원할 수 있습니다. 캡슐화를 위반하지 않습니다. 구현:
import java.util.ArrayList;
import java.util.List;
class Memento {
private String name;
private int age;
public Memento(String name, int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
System.out.println(String.format("create: name = %s, age = %s", name, age));
}
public Memento save(){
System.out.println(String.format("save: name = %s, age = %s", name, age));
return new Memento(name, age);
}
public void restore(Memento memento){
name = memento.getName();
age = memento.getAge();
System.out.println(String.format("restore: name = %s, age = %s", name, age));
}
}
class SaveUser {
private List<Memento> list = new ArrayList<Memento>();
public void add(Memento memento){
list.add(memento);
}
public Memento get(int ind){
return list.get(ind);
}
}
public class MementoTest { // Test
public static void main(String[] args) {
SaveUser saveUser = new SaveUser();
User user1 = new User("Peter", 17);
User user2 = new User("Ian", 19);
saveUser.add(user1.save());
user1.restore(saveUser.get(0));
}
}
행운을 빌어 요 프로그래밍!
더 읽어보기: |
---|
GO TO FULL VERSION