0
点赞
收藏
分享

微信扫一扫

学习鸿蒙基础(6)

就是耍帅 03-01 18:30 阅读 2

单例模式

单例模式保证一个类只能创建一个对象,并提供全局访问点。通常用于全局共享例如日志、数据库连接池等。

Lazy Initialization

        优点:需要时才初始化,节省空间

        缺点:线程不安全

class Singleton{
private:
    static Singleton* instance;//提供的静态成员
    Singleton() {}//重写构造函数为私有,禁止使用通常方法创建Singleton
public:
    //外界只能通过getInstance去获取静态成员,从而保证只有一个实例
    ststic Singleton* getInstance(){
        if(instance == nullptr)
            instance = new Singleton();//可能会有多个线程同时执行这句,导致问题
        return instance;
    }
}

Eager Initialization

        优点:线程安全

        缺点:不管用不用都会初始化,占空间

class Singleton{
private:
    static Singleton* instance;
    Singleton(){}
public:
    static Singleton* getInstance(){
        return instance;
    }
}

Singleton* Singleton::instance = new Singleton();

Double-Checked Locking

        优点:延迟加载、线程安全

        缺点:没有

#include <mutex>

class Singleton{
private:
    static volatile Singleton* instance;
    static std::mutex mtx;
    Singleton(){}
public:
    static volatile Singleton* getInstance(){
        if(instance == nullptr){
            std::lock_guard<std::mutex> lock(mtx);
            if(instance == nullptr){   //double-checked locking
                instance = new Singleton();
            }
        }
        return instance;    
    }
};

volatile Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mtx;

代理模式

我要租房,我不去租,找了个中介去租。

class Person{
public:
    virtual void rentHouse() = 0;//纯虚函数
};


class I : public Person{
public:
    void rentHouse(){
        std::cout << "I want to rent a house."<<endl;
    }
};


class Intermediary : public Person{
public: 
    Intermediary(Person * person) : m_person(person) {

    }

    void rentHouse(){
        m_person->rentHouse();
        std::cout << "I'am Intermediary."<<endl;
    }
private:
    Person *m_person;
};


void testDalegate()
{
    Person *i = new I();
    Person *intermediary = new Intermediary(i);
    intermediary->rentHouse();
}

简单工厂模式

简单工厂模式是一种实例化对象的方式,只要我们输入的实例化信息,就可以通过工厂方式实例化相应的实例化对象。

class TelPhone{
public:
    enum PhoneType{Mi, Oppo, Huawei};
    virtual void setName(std::string name) = 0;
    virtual void setPrice(double price) = 0;
    virtual double getPrice() = 0;
protected:
    std::string name;
    double price;
};

class MiPhone : public TelPhone{
public:    
    Miphone(){
        setname("mi15");
        setprice(1234)
    }
    std::string getName(){
        return TelPhone::name;
    }
    std::double getPrice(){
        return TelPhone::Price;
    }
    void setName(std::string name){
        TelPhone::name = name;
    }
    void setPrice(double price)
    {
        TelPhone::price = price;
    }
    
};
class OppoPhone : public TelPhone{
    //...
};
class HuaWeiPhone : public TelPhone{
    //...
};


class TelPhoneFactory{
public:
    //生产手机
    static TelPhone* productTelPhone(TelPhone::PhoneType phoneType)
    {
        TelPhone *telp = nullptr;
        swith(phoneType){
            case TelPhone::Mi:
                telp = new Miphone();
                break;
            case TelPhone::Oppo:
                telp = new Oppophone();
                break;
            case TelPhone::Huawei:
                telp = new Huaweiphone();
                break;
            default:
                break;
        }
        return telp;
    }    
};

void testFactory(){
    TelPhone *telp = TelPhoneFactory::productTelPhone(TelPhone::Mi);
    if(telp != nullptr){
        std::cout<<telp->getName() << std::endl;
        std::cout<<telp->getPrice() << std::endl;
    }
}

观察者模式

又叫发布-订阅模式,定义对象间一对多的关系,当一个对象状态发生变化时,其所有依赖者都会收到通知

原型模式

用一个以及创建的实例作为原型,通过复制该原型对象来创建一个和原型相同或者相似的对象。类似原件和复印件的关系。

策略模式

定义一系列算法,把他们一个个封装起来,并且使他们可以相互替换。通过策略模式,可以动态的选择、配置和切换算法,而无需修改客户端代码。

#include<iostream>

enum StrategyType{
    E_StrategyNight,
    E_StraegyWeekend,
};
class Strategy{
public:
    virtual void algorithm() = 0;
    virtual ~Strategy(){}
};

class StrategyNight : public Strategy{
public:
    void algorithm(){
        std::cout << "晚上加班计算方法"<<std::endl;
    }
    virtual ~StrategyNight(){}
};

class StraegyWeekend : public Strategy{
public:
    void algorithm(){
        std::cout<<"周末加班"<<std::endl;

    }
    virtual ~StraegyWeekend(){}
};

class Context{
public:
    Context(StrategyType strategyType)
    {
        switch (strategyType)
        {
        case E_StrategyNight:
            pStrategy = new StrategyNight();
            break;
        case E_StraegyWeekend:
            pStrategy = new StraegyWeekend();
            break;
        default:
            break;
        }
    }

    ~Context(){
        if(pStrategy)
            delete pStrategy;
    }

    void overtimePay(){
        if(pStrategy){
            pStrategy->algorithm();
        }
    }
private:
    Strategy* pStrategy;
};

int main(){
    Context *pcont = new Context(E_StraegyWeekend);
    pcont->overtimePay();
    if(pcont)
        delete pcont;

    return 0;
}

中介者模式

定义一个中介对象来封装一系列对象之间的交互,使得原有对象之间的耦合松散,且可以独立地改变他们之间的交互。

#include<iostream>
#include<vector>
#include<string>
using namespace std;

class Employee{
private:
    string m_strName;
    string m_strContent;
public:
    Employee(string strName) : m_strName(strName){

    }

    void setName(string strName){
        m_strName = strName;
    }

    string getName(){
        return m_strName;
    }

    void setContent(string content){
        m_strContent = content;
    }

    string getContent()
    {
        if(m_strContent.empty())
            return "收到";
        return m_strContent;
    }

    virtual void talk() = 0;
};

class Boss : public Employee{
public:
    Boss(string str) :Employee(str){}
    void talk(){
        cout << getName() << " says: " << getContent()<<endl;
    }
};

class Manager : public Employee{
public:
    Manager(string str) :Employee(str){}
    void talk(){
        cout << getName() << " says: " << getContent()<<endl;
    }
};
class Securtity: public Employee{
public:
    Securtity(string str) :Employee(str){}
    void talk(){
        cout << getName() << " says: " << getContent()<<endl;
    }
};

class  Mediator{
protected:
    vector<Employee*> vec_emp;

public:
    void addEmployee(Employee* emp){
        vec_emp.push_back(emp);
    }
    virtual void notify(Employee* emp) = 0;
};

class HolidaysMediator : public Mediator{
public:
    void notify(Employee* emp){ 
        emp->talk();

        for(int i = 0; i < vec_emp.size(); i++)
        {
            if(emp != vec_emp[i])
            {
                vec_emp[i]->talk();
            }
        }
    }
};

int main(){
    HolidaysMediator holidaysMediator;
    Boss* boss = new Boss("老板");
    Manager* manager = new Manager("经理");
    Securtity* securtity = new Securtity("保安");
    holidaysMediator.addEmployee(boss);
    holidaysMediator.addEmployee(manager);
    holidaysMediator.addEmployee(securtity);

    boss->setContent("明天放假");
    holidaysMediator.notify(boss);
    return 0;
    }

责任链模式

用来处理相关事务的一条执行链,执行链上有多个节点,每个节点都有机会处理请求事务,如果某个节点处理完就可以根据实际业务需求传递给下一个节点继续处理或者返回处理完毕。

#include<iostream>
using namespace std;

class Logger{
public:
    enum LEVEL {
        DEBUG,
        INFO,
        WARN,
        ERROR 
        };

    LEVEL m_level = LEVEL::DEBUG;

    Logger(){ }
    virtual ~Logger(){}

    void logMessage(LEVEL level, string message){
        if(m_level <= level)
        {
            write(message);
        }

        if(m_nextLogger != NULL)
        {
            m_nextLogger->logMessage(level, message);
        }
    }
    void setNextLogger(Logger* nextLogger){
        m_nextLogger = nextLogger;
    }
protected:
    virtual void write(string logger){};
    Logger* m_nextLogger;
};

class DebugLogger : public Logger{
public:
    DebugLogger(LEVEL level){
        m_level = level;
    }

    void write(string logger){
        cout << "Debug Logger: " << m_level<< ", message:"<<logger<<endl;

    }
};
class ErrorLogger : public Logger{
public:
    ErrorLogger(LEVEL level){
        m_level = level;
    }

    void write(string logger){
        cout << "Error Logger: " << m_level<< ", message:"<<logger<<endl;

    }
};

class InfoLogger : public Logger{
public:
    InfoLogger(LEVEL level){
        m_level = level;
    }

    void write(string logger){
        cout << "Info Logger: " << m_level<< ", message:"<<logger<<endl;

    }
};

class WarnLogger : public Logger{
public:
    WarnLogger(LEVEL level){
        m_level = level;
    }

    void write(string logger){
        cout << "Warn Logger: " << m_level<< ", message:"<<logger<<endl;

    }
};

class Client{
public:
    Client(){

    }
    ~Client(){}

    void test(){
        Logger *logger = getChainOfLoggers();
        logger->logMessage(Logger::DEBUG, "this is debug");
        cout << "--------------"<<endl;
        logger->logMessage(Logger::DEBUG, "this is info");
        cout << "--------------"<<endl;
        logger->logMessage(Logger::DEBUG, "this is warn");
        cout << "--------------"<<endl;
        logger->logMessage(Logger::DEBUG, "this is error");
    }
private:
    Logger* getChainOfLoggers(){
        Logger *debug = new DebugLogger(Logger::DEBUG);
        Logger *info = new InfoLogger(Logger::INFO);
        Logger *warn = new WarnLogger(Logger::WARN);
        Logger *error = new ErrorLogger(Logger::ERROR);

        error->setNextLogger(warn);
        warn->setNextLogger(info);
        info->setNextLogger(debug);

        return error;
    }
};

int main(){
    Client client;
    client.test();
    return 0;
}

举报

相关推荐

0 条评论