Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1742830
  • 博文数量: 297
  • 博客积分: 285
  • 博客等级: 二等列兵
  • 技术积分: 3006
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-06 22:04
个人简介

Linuxer, ex IBMer. GNU https://hmchzb19.github.io/

文章分类

全部博文(297)

文章存档

2020年(11)

2019年(15)

2018年(43)

2017年(79)

2016年(79)

2015年(58)

2014年(1)

2013年(8)

2012年(3)

分类: Java

2017-02-19 11:36:27

Strategy pattern also known as Policy Pattern. 

挺有意思的看了一个例子,将不通的Algorithm 设计为不同的类,然后通过一个Context 类联系在一起。


点击(此处)折叠或打开

  1. package policypattern;

  2. interface Strategy{
  3.     public void sort(int[] numbers);
  4. }

  5. class MyContext{
  6.     private Strategy strategy;

  7.     //constructor
  8.     public MyContext(Strategy strategy){
  9.         this.strategy= strategy;
  10.     }

  11.     public void arrange(int[] input){
  12.         strategy.sort(input);
  13.     }
  14. }

  15. class BubbleSort implements Strategy{
  16.     @Override
  17.     public void sort(int[] numbers){
  18.         System.out.println("Sorting array using bubble sort strategy");
  19.     }
  20. }

  21. class InsertionSort implements Strategy{

  22.     @Override
  23.     public void sort(int[] numbers){
  24.         System.out.println("Sorting array with insertion sort strategy");
  25.     }
  26. }


  27. class MergeSort implements Strategy{
  28.     @Override
  29.     public void sort(int[] numbers){
  30.         System.out.println("Sorting array using merge sort strategy");
  31.     }
  32. }

  33. class QuickSort implements Strategy{
  34.     @Override
  35.     public void sort(int[] numbers){
  36.         System.out.println("Sorting array using quick sort strategy");
  37.     }
  38. }



  39. public class StrategyPatternDemo {
  40.     public static void main(String[] args){
  41.         int[] var = {1,2,9,6,4,10};

  42.         //provide any strategy to do the sorting
  43.         MyContext ctx = new MyContext(new BubbleSort());
  44.         ctx.arrange(var);

  45.         //we can change the Strategy without changing Context class
  46.         ctx = new MyContext(new QuickSort());
  47.         ctx.arrange(var);
  48.     }
  49. }

阅读(868) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~