JavaRush /Java Blog /Random-KO /Java의 디자인 패턴 [2부]
Ivan Zaitsev
레벨 33
Киев

Java의 디자인 패턴 [2부]

Random-KO 그룹에 게시되었습니다
안녕하세요 여러분. 이전 주제 에서는 각 패턴을 간략하게 설명했는데, 이번 주제에서는 패턴 사용 방법을 자세히 보여 드리겠습니다.
Java의 디자인 패턴 [2부] - 1

생성

하나씩 일어나는 것

설명 :
  • 클래스 인스턴스 하나만 생성하는 것을 제한하고 해당 클래스의 유일한 개체에 대한 액세스를 제공합니다. 클래스 생성자는 비공개입니다. 이 메서드는 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 {//тест
    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("применить для виндовс");
    }
}
class linuxOS implements OS {
    public void getOS () {
        System.out.println("применить для линукс");
    }
}
class macOS implements OS {
    public void getOS () {
        System.out.println("применить для мак");
    }
}

public class FactoryTest {//тест
    public static void main(String[] args){
        String win = "linux";
        Factory factory = new Factory();
        OS os = factory.getCurrentOS(win);
        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 {// первая
    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();
    }
}// первая
class RuLadaImpl implements Lada {// вторая
    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();
    }
}// вторая

public class AbstractFactoryTest {//тест
    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("Doing корпус");
    }
    public void buildWheels() {
        print("Ставим колесо");
    }
    public void buildEngine(Engine engine) {
        print("Ставим движок: " + engine.getEngineType());
    }
    private void print(String msg){
        System.out.println(msg);
    }
}
interface Engine {
    String getEngineType();
}
class OneEngine implements Engine {
    public String getEngineType() {
        return "Первый двигатель";
    }
}
class TwoEngine implements Engine {
    public String getEngineType() {
        return "Второй двигатель";
    }
}
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 OneEngine();
        car.buildEngine(engine);
        return car;
    }
}
class TwoBuilderImpl extends Builder {
    public TwoBuilderImpl(){
        car = new Car();
    }
    public Car buildCar() {
        car.buildBase();
        car.buildWheels();
        Engine engine = new OneEngine();
        car.buildEngine(engine);
        car.buildWheels();
        engine = new TwoEngine();
        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 {//тест
    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 {//тест
    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 {//тест
	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 SportCar implements Car {
    public void draw(String color) {
        System.out.println("SportCar 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 {//тест
    public static void main(String[] args) {
        Car sportCar = new SportCar();
        Car unknownCar = new UnknownCar();
        Drawing drawing = new Drawing();
        drawing.add(sportCar);
        drawing.add(unknownCar);
        drawing.draw("green");
        drawing.clear();
        drawing.add(sportCar);
        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("Загрузка " + file);
    }
    public void display() {
        System.out.println("Просмотр " + 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 {//тест
    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 {//тест
    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("Вставить ключи");
    }
    public void stop() {
        System.out.println("Вытянуть ключи");
    }
}
class Engine implements Car {
    public void start() {
        System.out.println("Запустить двигатель");
    }
    public void stop() {
        System.out.println("Остановить двигатель");
    }
}
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 {//тест
    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 SportCar extends Car {
    public SportCar(Engine engine) {
        super(engine);
    }
    public void setEngine() {
        System.out.print("SportCar engine: ");
        engine.setEngine();
    }
}
class UnknownCar extends Car {
    public UnknownCar(Engine engine) {
        super(engine);
    }
    public void setEngine() {
        System.out.print("UnknownCar engine: ");
        engine.setEngine();
    }
}
class SportEngine implements Engine {
    public void setEngine(){
        System.out.println("sport");
    }
}
class UnknownEngine implements Engine {
    public void setEngine(){
        System.out.println("unknown");
    }
}
public class BridgeTest {//тест
    public static void main(String[] args) {
        Car sportCar = new SportCar(new SportEngine());
        sportCar.setEngine();
        System.out.println();
        Car unknownCar = new UnknownCar(new UnknownEngine());
        unknownCar.setEngine();
    }
}

데코레이터

설명 :
  • 구조를 바인딩하지 않고 기존 개체에 새 기능을 추가합니다.
구현:
interface Car {
    void draw();
}
class SportCar implements Car {
    public void draw() {
        System.out.println("SportCar");
    }
}
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 {//тест
    public static void main(String[] args) {
        Car sportCar = new SportCar();
        Car blueUnknownCar = new BlueCarDecorator(new UnknownCar());
        sportCar.draw();
        System.out.println();
        blueUnknownCar.draw();
    }
}

행동

템플릿 방법

설명 :
  • 알고리즘의 기초를 정의할 수 있으며 하위 클래스가 전체 구조를 변경하지 않고도 알고리즘의 특정 단계를 재정의할 수 있습니다.
구현:
abstract class Car {
    abstract void startEngine();
    abstract void stopEngine();

    public final void start(){
        startEngine();
        stopEngine();
    }
}
class OneCar extends Car {
    public void startEngine() {
        System.out.println("Start engine.");
    }
    public void stopEngine() {
        System.out.println("Stop engine.");
    }
}
class TwoCar extends Car {
    public void startEngine() {
        System.out.println("Start engine.");
    }
    public void stopEngine() {
        System.out.println("Stop engine.");
    }
}

public class TemplateTest {//тест
    public static void main(String[] args) {
        Car car1 = new OneCar();
        car1.start();
        System.out.println();
        Car car2 = new TwoCar();
        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 {//тест
    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 {//тест
    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 {//тест
    public static void main(String[] args) {
        University university = new University();
        Director director = new Director();
        university.addStudent("Vaska");
        university.addObserver(director);
        university.addStudent("Anna");
        university.removeStudent("Vaska");
    }
}

전략

설명 :
  • 이들 간의 상호 작용을 허용하는 여러 알고리즘을 정의합니다. 전략 알고리즘은 프로그램 실행 중에 변경될 수 있습니다.
구현:
interface Strategy {
    void download(String file);
}
class DownloadWindownsStrategy implements Strategy {
    public void download(String file) {
        System.out.println("windows download: " + file);
    }
}
class DownloadLinuxStrategy 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 {//тест
    public static void main(String[] args) {
        Context context = new Context(new DownloadWindownsStrategy());
        context.download("file.txt");
        context = new Context(new DownloadLinuxStrategy());
        context.download("file.txt");
    }
}

명령

설명 :
  • 다양한 작업을 별도의 객체로 캡슐화할 수 있습니다.
구현:
interface Command {
    void execute();
}
class Car {
    public void startEngine() {
        System.out.println("запустить двигатель");
    }
    public void stopEngine() {
        System.out.println("остановить двигатель");
    }
}
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 {//тест
    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 {//тест
    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(SportCar sportCar);
    void visit(Engine engine);
    void visit(Whell whell);
}
interface Car {
    void accept(Visitor visitor);
}
class Engine implements Car {
    public void accept(Visitor visitor) {
        visitor.visit(this);
    }
}
class Whell implements Car {
    public void accept(Visitor visitor) {
        visitor.visit(this);
    }
}
class SportCar implements Car {
    Car[] cars;
    public SportCar(){
        cars = new Car[]{new Engine(), new Whell()};
    }
    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(SportCar computer) {
        print("car");
    }
    public void visit(Engine engine) {
        print("engine");
    }
    public void visit(Whell whell) {
        print("whell");
    }
    private void print(String string) {
        System.out.println(string);
    }
}

public class VisitorTest {//тест
    public static void main(String[] args) {
        Car computer = new SportCar();
        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 LoverExpression(String s) {
        this.s = s;
    }
    public String interpret(Context context) {
        return context.getLoverCase(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 {//тест
    public static void main(String[] args) {
        String str = "TesT";
        Context context = new Context();
        Expression loverExpression = new LoverExpression(str);
        str = loverExpression.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 {//тест
    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.
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION