[Design Pattern] Verhaltensmuster: Strategy

Thomas Darimont

Erfahrenes Mitglied
Hallo,

dieser Beitrag erklärt das Verhaltensmuster: Strategy

Java:
package com.dacos.training.java.patterns.behavioral;

public class StrategyPatternExample {

	public static void main(String[] args) {
		CoffeMachine cm = new CoffeMachine();
		cm.makeCoffe(CoffeType.ESPRESSO);
		cm.makeCoffe(CoffeType.LATTE);
	}

	static class CoffeMachine {

		public void makeCoffe(CoffeType type) {
			selectStrategy(type).cook();
		}

		private CoffeCookingStrategy selectStrategy(CoffeType type) {
			switch (type) {
			case LATTE:
				return new LatteCoffeCookingStrategy();
			case ESPRESSO:
				return new EspressoCoffeCookingStrategy();
			}
			return null;
		}
	}

	static interface CoffeCookingStrategy {
		void cook();
	}

	static class LatteCoffeCookingStrategy implements CoffeCookingStrategy {
		@Override
		public void cook() {
			System.out.println("Cooking latte");
		}
	}

	static class EspressoCoffeCookingStrategy implements CoffeCookingStrategy {
		@Override
		public void cook() {
			System.out.println("Cooking Espresso");
		}
	}
	
	enum CoffeType {
		LATTE, ESPRESSO
	}
}

Ausgabe:
Code:
Cooking Espresso
Cooking latte



Gruß Tom
 
Hi
Würde man eigentlich, wenn man eine Strategie rein hängen könnte, anstelle der Fallunterscheidung mit dem "Funkionscode" auch noch von Strategy-Patten sprechen, ode wäre das dann was anderes?
 
Hallo,

Würde man eigentlich, wenn man eine Strategie rein hängen könnte, anstelle der Fallunterscheidung mit dem "Funkionscode" auch noch von Strategy-Patten sprechen, ode wäre das dann was anderes?
Ja - im obigen Beispiel habe ich nur die Strategie-Wahl in Abhängigkeit vom Strategy-Context dynamisiert.

Schau mal hier:
Java:
class CoffeMachine {

  private final CoffeCookingStrategy coffeCookingStrategy;

  public CoffeMachine(CoffeCookingStrategy coffeCookingStrategy) {
    this.coffeCookingStrategy = coffeCookingStrategy;
  }


  public void makeCoffe() {
    coffeCookingStrategy.cook();
  }
}


interface CoffeCookingStrategy {
  void cook();
}


class LatteCoffeCookingStrategy implements CoffeCookingStrategy {
  @Override
  public void cook() {
    System.out.println("Cooking latte");
  }
}


class EspressoCoffeCookingStrategy implements CoffeCookingStrategy {
  @Override
  public void cook() {
    System.out.println("Cooking Espresso");
  }
}


enum CoffeType {
  LATTE, ESPRESSO
}


public class StrategyPatternExample {

  public static void main(String[] args) {
    new CoffeMachine(new LatteCoffeCookingStrategy()).makeCoffe();
    new CoffeMachine(new EspressoCoffeCookingStrategy()).makeCoffe();
  }
}



Gruß Tom
 
Zurück