zoukankan      html  css  js  c++  java
  • Design Pattern 设计模式1

    实现 : Defferent Heros attack Defferently. - 不同的英雄使用不用的招数


    Strategy设计的思路:

    基类A。更加小的基类B,新的继承类C:

    1 从基类A中抽出一个更加小的基类B

    2 利用这个更加小的基类B实现不同的效果

    3 把这个更加小的基类B包括进基类A中去

    4 新的继承类C仅仅须要和基类A打交道,设计不同行为,不须要理会更加小的基类B


    #pragma once
    #ifndef _STRATEGY_HEROS_H
    #define _STRATEGY_HEROS_H
    
    #include <stdio.h>
    
    //Interface
    class HeroAttack
    {
    public:
    	virtual void attack() = 0;
    };
    
    //Base method class
    class Laser : public HeroAttack
    {
    public:
    	void attack()
    	{
    		puts("Super Eye-Laser");
    	}
    };
    
    class Smash : public HeroAttack
    {
    public:
    	void attack()
    	{
    		puts("I smash!");
    	}
    };
    
    class WebWebWeb : public HeroAttack
    {
    public:
    	void attack()
    	{
    		puts("Web, Web, Web!");
    	}
    };
    
    //Base Class
    class Hero_From_Marvel
    {
    	HeroAttack *heroAtt;
    protected:
    	void setAttackWay(HeroAttack *hat)
    	{
    		if (heroAtt) delete heroAtt;
    		heroAtt = hat;
    	}
    public:
    	Hero_From_Marvel() : heroAtt(nullptr)
    	{
    	}
    
    	virtual ~Hero_From_Marvel()
    	{
    		if (heroAtt) delete heroAtt;
    		heroAtt = nullptr;
    	}
    
    	void attack()
    	{
    		heroAtt->attack();
    	}
    };
    
    //derived class
    class SuperMan : public Hero_From_Marvel
    {
    public:
    	SuperMan()
    	{
    		setAttackWay(new Laser);//这里不能使用malloc,否则内存冲突
    	}
    };
    
    class Hulk : public Hero_From_Marvel
    {
    public:
    	Hulk()
    	{
    		setAttackWay(new Smash);
    	}
    };
    
    class SpiderMan : public Hero_From_Marvel
    {
    public:
    	SpiderMan()
    	{
    		setAttackWay(new WebWebWeb);
    	}
    };
    
    int StrategyHerosRun()
    {
    	const int HEROS = 3;
    	Hero_From_Marvel *hfm[HEROS] = {new SuperMan, new Hulk, new SpiderMan};
    	for (int i = 0; i < HEROS; i++)
    	{
    		hfm[i]->attack();
    		delete hfm[i];
    	}
    	return 0;
    }
    
    #endif





  • 相关阅读:
    codeforces 图论题目集(持续更新)
    整数快速幂
    Codeforces Codeforces Global Round 5 C2
    POJ 1061
    扩展欧几里德算法(数论)
    Codeforces Round #592 (Div. 2) 1224D
    Codeforces Round #582 (Div. 3) G. Path Queries
    2019 kickstart A轮 B 题
    P3379 【模板】最近公共祖先(LCA)
    bzoj 2002 分块
  • 原文地址:https://www.cnblogs.com/tlnshuju/p/6931834.html
Copyright © 2011-2022 走看看