Javaデザインパターン

# デザインパターンの備忘録
Paiza.ioを使ってデザインパターンを作成し忘れないように記録しておきます。

# Facadeパターン
### Online Editer Piza.ioで実装
```Main.java
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        // Your code here!
    LibraryFacade lf = new LibraryFacade();
    lf.findAndLoanBook("Design patterns for Beginers in Java");
    lf.returnBook("Design patterns for professionals in C#");
    }
}

class BookSearch{
  public void search(String bookTitle){
    System.out.println("Book" + bookTitle + " is searching...");
  }
}

class BookLoan{
  public void loan(String bookTitle){
    System.out.println("Book" + bookTitle + " has been loaned.");
  }
}

class BookReturn{
  public void returnBook(String bookTitle){
    System.out.println("Book" + bookTitle + " had returned.");
  }
}

class LibraryFacade{
  private BookSearch searcher;
  private BookLoan loaner;
  private BookReturn retuner;

  public LibraryFacade(){
    this.searcher = new BookSearch();
    this.loaner = new BookLoan();
    this.retuner = new BookReturn();
  }

  public void findAndLoanBook(String bookTitle){
    searcher.search(bookTitle);
    loaner.loan(bookTitle);
  }

  public void returnBook(String bookTitle){
    retuner.returnBook(bookTitle);
  }
}

```
#### 実行結果
```
BookDesign patterns for Beginers in Java is searching...
BookDesign patterns for Beginers in Java has been loaned.
BookDesign patterns for professionals in C# had returned.
```

# Visitorパターン

https://cs-techblog.com/technical/visitor-pattern/

```Main.java
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Element elementA = new ConcreteElementA();
        Element elementB = new ConcreteElementB();
        
        Visitor visit = new ConcreteVisitor();
        elementA.accept(visit);
        elementB.accept(visit);
    }
}

interface Visitor{
    void visit(ConcreteElementA element);
    void visit(ConcreteElementB element);
}

class ConcreteVisitor implements Visitor{
    public void visit(ConcreteElementA element){
        System.out.println("ConcreteElementAを処理中");
    }
    
    public void visit(ConcreteElementB element){
        System.out.println("ConcreteElementBを処理中");
    }
}

interface Element{
    void accept(Visitor visitor);
}

class ConcreteElementA implements Element{
    public void accept(Visitor visitor){
        visitor.visit(this);
    }
}

class ConcreteElementB implements Element{
    public void accept(Visitor visitor){
        visitor.visit(this);
    }
}
```

#### 実行結果
```
ConcreteElementAを処理中
ConcreteElementBを処理中
```

# Strategyパターン

https://cs-techblog.com/technical/strategy-pattern/

```Main.java
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Context context = new Context(new OperationAdd());
        System.out.println("10 + 5 = " + context.executeStrategy(10,5));
        
        context = new Context(new OperationSubstract());
        System.out.println("10 - 5 = " + context.executeStrategy(10,5));
    }
}

interface Strategy{
    public int doOpertion(int num1,int num2);
}

class OperationAdd implements Strategy{
    public int doOpertion(int num1, int num2){
        return num1 + num2;
    }
}

class OperationSubstract implements Strategy{
    public int doOpertion(int num1, int num2){
        return num1 - num2;
    }
}

class Context{
    private Strategy strategy;
    
    public Context(Strategy strategy){
        this.strategy = strategy;
    }
    
    public int executeStrategy(int num1,int num2){
        return strategy.doOpertion(num1,num2);
    }
}

```

#### 実行結果
```
10 + 5 = 15
10 - 5 = 5
```

# Stateパターン

https://cs-techblog.com/technical/state-pattern/

```Main.java
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Context context = new Context();
        StartState startState = new StartState();
        startState.doAction(context);
        
        System.out.println(context.getState().toString());
        
        StopState stopState = new StopState();
        stopState.doAction(context);
        
        System.out.println(context.getState().toString());
    }
}

interface State{
    void doAction(Context context);
}

class StartState implements State{
    public void doAction(Context context){
        System.out.println("Player is in start state");
        context.setState(this);
    }
    
    public String toString(){
        return "Start State";
    }
}

class StopState implements State{
    public void doAction(Context context){
        System.out.println("Player is in stop state");
        context.setState(this);
    }
    
    public String toString(){
        return "Stop State";
    }
}

class Context{
    private State state;
    
    public Context(){
        state = null;
    }
    
    public void setState(State state){
        this.state = state;
    }
    
    public State getState(){
        return state;
    }
}

```
#### 実行結果
```
Player is in start state
Start State
Player is in stop state
Stop State
```

# Builderパターン

https://cs-techblog.com/technical/builder-pattern/

```Main.java
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        CarBuilder builder = new SportsCarBuilder();
        Director director = new Director(builder);
        director.constructCar();
        
        Car car = builder.getCar();
        
        System.out.println(car);
    }
}

class Car{
    private String engine;
    private String wheels;
    private String interior;
    
    
    public Car(String engine,String wheels,String interior){
        this.engine = engine;
        this.wheels = wheels;
        this.interior = interior;
    }
    
    @Override
    public String toString(){
        return "Car [Engine=" + engine + ", Wheels=" + wheels + ", Interior=" + interior + "]";
    }
}

interface CarBuilder{
    void buildEngine();
    void buildWheels();
    void buildInterior();
    Car getCar();
}

class SportsCarBuilder implements CarBuilder{
    private String engine;
    private String wheels;
    private String interior;
    
    @Override
    public void buildEngine(){
        engine = "V8 engine";
    }
    
    @Override
    public void buildWheels(){
        wheels = "Sports Wheels";
    }
    
    @Override
    public void buildInterior(){
        interior = "Leather Interior";
    }
    
    @Override
    public Car getCar(){
        return new Car(engine,wheels,interior);
    }
}

class Director{
    private CarBuilder carBuilder;
    
    public Director(CarBuilder carBuilder){
        this.carBuilder = carBuilder;
    }
    
    public void constructCar(){
        carBuilder.buildEngine();
        carBuilder.buildWheels();
        carBuilder.buildInterior();
    }
}

```

#### 実行結果
```
Car [Engine=V8 engine, Wheels=Sports Wheels, Interior=Leather Interior]
```

# Mementoパターン

https://cs-techblog.com/technical/memento-pattern/

```Main.java
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Originator originator = new Originator();
        CareTaker careTaker = new CareTaker();
        
        originator.setState("State #1");
        careTaker.add(originator.saveStateToMemento());
        
        originator.setState("State #2");
        careTaker.add(originator.saveStateToMemento());
        
        originator.setState("State #3");
        
        System.out.println("Current State: " + originator.getState());
        originator.getStateFromMemento(careTaker.get(0));
        System.out.println("First saved State: " + originator.getState());
        originator.getStateFromMemento(careTaker.get(1));
        System.out.println("Second saved State: " + originator.getState());
    }
}

class Memento{
    private String state;
    public Memento(String state){
        this.state = state;
    }
    
    public String getState(){
        return state;
    }
}

class Originator{
    private String state;
    
    public void setState(String state){
        this.state = state;
    }
    
    public String getState(){
        return state;
    }
    
    public Memento saveStateToMemento(){
        return new Memento(state);
    }
    
    public void getStateFromMemento(Memento memento){
        state = memento.getState();
    }
}

class CareTaker{
    private List<Memento> mementoList = new ArrayList<>();
    
    public void add(Memento state){
        mementoList.add(state);
    }
    
    public Memento get(int index){
        return mementoList.get(index);
    }
}
```

#### 実行結果

```
Current State: State #3
First saved State: State #1
Second saved State: State #2
```

# Interpreterパターン

https://cs-techblog.com/technical/interpreter-pattern/

```Main.java
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Expression expression = new Substract(
            new Add(new Number(5),new Number(3)),
            new Number(2)
        );
        
        System.out.println("結果: " + expression.interpret()); 
    }
}

interface Expression{
    int interpret();
}

class Number implements Expression{
    private int number;
    
    public Number(int number){
        this.number = number;
    }
    
    @Override
    public int interpret(){
        return this.number;
    }
}

class Add implements Expression{
    private Expression leftExpression;
    private Expression rightExpression;
    
    public Add(Expression leftExpression,Expression rightExpression){
        this.leftExpression = leftExpression;
        this.rightExpression = rightExpression;
    }
    
    @Override
    public int interpret(){
        return leftExpression.interpret() + rightExpression.interpret();
    }
}

class Substract implements Expression{
    private Expression leftExpression;
    private Expression rightExpression;
    
    public Substract(Expression leftExpression,Expression rightExpression){
        this.leftExpression = leftExpression;
        this.rightExpression = rightExpression;
    }
    
    @Override
    public int interpret(){
        return leftExpression.interpret() - rightExpression.interpret();
    }
    
}



```

#### 実行結果

```
結果: 6
```