[JAVA] Design pattern ~ Strategy ~

1.First of all

We will summarize the ** Strategy pattern ** in the GoF design pattern.

2. What is the Strategy pattern?

--The English word Strategy means ** Strategy **. In the case of programming, you can think of it as an ** algorithm **. --Any program is written to solve a problem. A specific algorithm is implemented to solve the problem. The Strategy pattern is a method that allows you to exchange the part that implements the algorithm. --The GoF design patterns are classified as ** behavioral design patterns **.

3. Sample class diagram

Strategy.PNG

4. Sample program

It is a program to play rock-paper-scissors. There is a strategy to move randomly and a strategy to move only Goo.

4-1. Hand class

This class represents the hand of rock-paper-scissors.

Hand.java


public class Hand {

	public static final int HANDVALUE_GUU = 0;
	public static final int HANDVALUE_CHO = 1;
	public static final int HANDVALUE_PAA = 2;

	public static final Hand[] hand = {
			new Hand(HANDVALUE_GUU),
			new Hand(HANDVALUE_CHO),
			new Hand(HANDVALUE_PAA),
	};

	private int handvalue;

	private Hand(int handvalue) {
		this.handvalue = handvalue;
	}

	public static Hand getHand(int handvalue) {
		return hand[handvalue];
	}

	public boolean isStrongerThan(Hand h) {
		//true when this is stronger than h
		return fight(h) == 1;
	}

	private int fight(Hand h) {
		if (this == h) {
			//draw
			return 0;
		} else if ((this.handvalue + 1) % 3 == h.handvalue) {
			//this win
			return 1;
		} else {
			//h win
			return -1;
		}
	}
}

4-2. Player class

This class represents the player who plays rock-paper-scissors.

Player.java


public class Player {

	private String name;
	private Strategy strategy;
	private int wincount;
	private int losecount;
	private int gamecount;

	public Player(String name, Strategy strategy) {
		this.name = name;
		this.strategy = strategy;
	}

	public String getName() {
		return name;
	}

	public Hand nextHand() {
		return strategy.nextHand();
	}

	public void win() {
		wincount++;
		gamecount++;
	}

	public void lose() {
		losecount++;
		gamecount++;
	}

	public void even() {
		gamecount++;
	}

	public String toString() {
		return "[" + name + "] " + gamecount + " gemes, " + wincount + " win, " + losecount + " lose";
	}
}

4-3. Strategy interface

It is an interface that represents the "strategy" of rock-paper-scissors.

Strategy.java


public interface Strategy {
	public abstract Hand nextHand();
}

4-4. RandomStrategy class

This is a class that represents a strategy to make random moves.

RandomStrategy.java


import java.util.Random;

public class RandomStrategy implements Strategy {

	public Hand nextHand() {
		Random random = new Random();
		return Hand.getHand(random.nextInt(3));
	}
}

4-5. GuuStrategy class

This class represents a strategy that only Goo can do.

GuuStrategy.java


public class GuuStrategy implements Strategy {

	public Hand nextHand() {
		return Hand.getHand(Hand.HANDVALUE_GUU);
	}
}

4-6. Main class

This class performs the main processing.

Main.java


public class Main {

	public static void main(String[] args) {

		Player player1 = new Player("Taro", new RandomStrategy());
		Player player2 = new Player("Hana", new GuuStrategy());
		for (int i = 0; i < 5; i++) {
			Hand nextHand1 = player1.nextHand();
			Hand nextHand2 = player2.nextHand();
			if (nextHand1.isStrongerThan(nextHand2)) {
				System.out.println("Winner:" + player1.getName());
				player1.win();
				player2.lose();
			} else if (nextHand2.isStrongerThan(nextHand1)) {
				System.out.println("Winner:" + player2.getName());
				player1.lose();
				player2.win();
			} else {
				System.out.println("Even...");
				player1.even();
				player2.even();
			}
		}

		System.out.println("----- Total result -----");
		System.out.println(player1.toString());
		System.out.println(player2.toString());
	}
}

4-7. Execution result

Winner:Taro
Winner:Hana
Even...
Winner:Hana
Even...
----- Total result -----
[Taro] 5 gemes, 1 win, 2 lose
[Hana] 5 gemes, 2 win, 1 lose

5. Benefits

The Strategy pattern consciously separates the algorithm part from the rest. Then, only the part of the interface with the algorithm is specified, and the algorithm is used by delegation. This seems to complicate the program, but it's not. For example, if you want to improve the algorithm and make it faster, if you are using the Strategy pattern, you can add or modify only the algorithm without changing the interface of the Strategy role. It uses a loose bond called delegation, so you can easily switch between algorithms. It can also be used to switch the difficulty level according to the user's selection in game programs.

  1. GitHub

7. List of design patterns

-** GoF design pattern summary **

8. Reference

This article and sample program were created based on the following books.

-** Introduction to design patterns learned in Java language **

It was very easy to understand and I learned a lot. Thank you. The detailed explanations of design patterns and sample programs are written, so please take a look at the books as well.

Recommended Posts

Design pattern ~ Strategy ~
Strategy pattern
Strategy Pattern
Design pattern ~ Builder ~
[Java] Strategy pattern
Design pattern ~ Visitor ~
Java design pattern
Design pattern ~ Proxy ~
Design pattern ~ State ~
Design pattern ~ Singleton ~
Design pattern ~ Composite ~
Design pattern (2): Builder
Design pattern (1): AbstractFactory
Design pattern ~ Command ~
Design pattern ~ Iterator ~
Design pattern ~ Facade ~
Design pattern ~ Bridge ~
Design pattern ~ Mediator ~
Design pattern ~ Decorator ~
Design pattern ~ Interpreter ~
Design pattern ~ Observer ~
Design pattern ~ Prototype ~
Design pattern ~ Memento ~
Design pattern ~ Adapter ~
Design pattern ~ Flyweight ~
C ++ design pattern (TemplateMethod pattern)
Design pattern ~ Factory Method ~
Design pattern ~ Abstract Factory ~
GoF design pattern summary
Design pattern ~ Template Method ~
Java design pattern summary
Design pattern ~ Chain of Responsibility ~
[Design pattern] Java core library
Enum Strategy pattern in Java
Introduction to Design Patterns (Strategy)
Ruby design pattern template method pattern memo
C # chewed design pattern: Template Method
Application example of design pattern (No. 1)
Java beginner design pattern (Factory Method pattern)
Prototype pattern
Memento Pattern
What a Strategy pattern Factory, not a State
Mediator pattern
Iterator pattern
Composite pattern
Builder pattern
Bridge Pattern
Command Pattern
Builder Pattern
Iterator Pattern
Visitor pattern
Adapter Pattern
Proxy Pattern
Composite Pattern
Singleton Pattern
Singleton pattern
Prototype Pattern
[Design pattern] Common logic with Template Method
Facade Pattern
Decorator pattern
Flyweight Pattern