add Strategy Pattern

master
FengJungle 2019-11-09 21:25:30 +08:00
parent ba025cb044
commit d12d406ed1
6 changed files with 164 additions and 1 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

View File

@ -0,0 +1,44 @@
#ifndef __CONTEXT_H__
#define __CONTEXT_H__
#include "Strategy.h"
#include <stdio.h>
// ÉÏÏÂÎÄÀà
class Context
{
public:
Context(){
arr = NULL;
N = 0;
}
Context(int iArr[], int iN){
this->arr = iArr;
this->N = iN;
}
void setSortStrategy(Strategy* iSortStrategy){
this->sortStrategy = iSortStrategy;
}
void sort(){
this->sortStrategy->sort(arr, N);
printf("Êä³ö£º ");
this->print();
}
void setInput(int iArr[], int iN){
this->arr = iArr;
this->N = iN;
}
void print(){
for (int i = 0; i < N; i++){
printf("%3d ", arr[i]);
}
printf("\n");
}
private:
Strategy* sortStrategy;
int* arr;
int N;
};
#endif // __CONTEXT_H__

View File

@ -0,0 +1,87 @@
#ifndef __STRATEGY_H__
#define __STRATEGY_H__
#include <stdio.h>
// 抽象策略类
class Strategy
{
public:
Strategy(){}
virtual void sort(int arr[], int N) = 0;
};
// 具体策略:冒泡排序
class BubbleSort :public Strategy
{
public:
BubbleSort(){
printf("冒泡排序\n");
}
void sort(int arr[], int N){
for (int i = 0; i<N; i++)
{
for (int j = 0; j<N - i - 1; j++)
{
if (arr[j]>arr[j + 1]){
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
}
};
// 具体策略:选择排序
class SelectionSort :public Strategy
{
public:
SelectionSort(){
printf("选择排序\n");
}
void sort(int arr[], int N){
int i, j, k;
for (i = 0; i<N; i++)
{
k = i;
for (j = i + 1; j<N; j++)
{
if (arr[j] < arr[k]){
k = j;
}
}
int temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
}
}
};
// 具体策略:插入排序
class InsertSort :public Strategy
{
public:
InsertSort(){
printf("插入排序\n");
}
void sort(int arr[], int N){
int i, j;
for (i = 1; i<N; i++)
{
for (j = i - 1; j >= 0; j--)
{
if (arr[i]>arr[j]){
break;
}
}
int temp = arr[i];
for (int k = i - 1; k > j; k--){
arr[k + 1] = arr[k];
}
arr[j + 1] = temp;
}
}
};
#endif

View File

@ -0,0 +1,28 @@
#include "Context.h"
#include <stdio.h>
#include <stdlib.h>
int main()
{
Context* ctx = new Context();
int arr[] = { 10, 23, -1, 0, 300, 87, 28, 77, -32, 2 };
ctx->setInput(arr, sizeof(arr)/sizeof(int));
printf("输入:");
ctx->print();
// 冒泡排序
ctx->setSortStrategy(new BubbleSort());
ctx->sort();
// 选择排序
ctx->setSortStrategy(new SelectionSort());
ctx->sort();
// 插入排序
ctx->setSortStrategy(new InsertSort());
ctx->sort();
printf("\n\n");
system("pause");
return 0;
}

View File

@ -97,4 +97,8 @@ Jungle设计模式系列
24.设计模式(二十四)——状态模式
博客地址https://blog.csdn.net/sinat_21107433/article/details/102966121
博客地址https://blog.csdn.net/sinat_21107433/article/details/102966121
25.设计模式(二十五)——策略模式
博客地址https://blog.csdn.net/sinat_21107433/article/details/102984862