java设计模式行为模式Behavioral Pattern策略模式Strategy Pattern
Posted xiongjiawei
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java设计模式行为模式Behavioral Pattern策略模式Strategy Pattern相关的知识,希望对你有一定的参考价值。
1 package com.tn.策略模式; 2 3 public class Client { 4 private Strategy strategy; 5 public void setStrategy(Strategy strategy){ 6 this.strategy=strategy; 7 } 8 public void exeAlgorithm() { 9 strategy.exeAlgorithm(); 10 } 11 12 public static void main(String[]args){ 13 Strategy strategy1=new ConcreteStrategy1(); 14 Strategy strategy2=new ConcreteStrategy2(); 15 Strategy strategy3=new ConcreteStrategy3(); 16 17 Client c=new Client(); 18 19 c.setStrategy(strategy1); 20 c.exeAlgorithm(); 21 22 c.setStrategy(strategy2); 23 c.exeAlgorithm(); 24 25 c.setStrategy(strategy3); 26 c.exeAlgorithm(); 27 } 28 } 29 interface Strategy{ 30 void exeAlgorithm(); 31 } 32 class ConcreteStrategy1 implements Strategy{ 33 @Override 34 public void exeAlgorithm() { 35 System.out.println("执行算法1……"); 36 } 37 } 38 class ConcreteStrategy2 implements Strategy{ 39 @Override 40 public void exeAlgorithm() { 41 System.out.println("执行算法2……"); 42 } 43 } 44 class ConcreteStrategy3 implements Strategy{ 45 @Override 46 public void exeAlgorithm() { 47 System.out.println("执行算法3……"); 48 } 49 }
以上是关于java设计模式行为模式Behavioral Pattern策略模式Strategy Pattern的主要内容,如果未能解决你的问题,请参考以下文章
编程思想设计模式行为模式Behavioral备忘录模式Memento
编程思想设计模式行为模式Behavioral观察者模式Observer
编程思想设计模式行为模式BehavioralSpecification