栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

(C++)设计模式

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

(C++)设计模式

1、设计原则

(1)开放封闭原则:类的改动是通过增加代码进行的,而不是修改代码
(2)依赖倒置原则:依赖于抽象,不要依赖于具体的实现(类),也就是针对接口编程

#include 
using namespace std;

class BankWorker   //抽象类
{
    public:
        virtual void Worker() = 0;

};

class GetMoney:public BankWorker 
{
    public:
        void Worker()                   //虚函数重写
        {
            cout<<"取款业务"<Worker();
    delete b;

    b = new SaveMoney;
    b->Worker();
    delete b;
    
    return 0;
}
2、依赖倒置原则

实列:电脑:硬盘、CPU

#include 
using namespace std;

class HardDisk
{
    public:
        virtual void Work() = 0;
};

class CPU
{
    public:
        virtual void Work() = 0;
};

class AHardDisk:public HardDisk
{
    public:
        void Work()
        {
            cout<<"AHard Disk work"<Work();
            m_c->Work();
        }
};

int main(int argc, char const *argv[])
{
    CPU *c = new ACPU;                 //c指向 ACPU,相当于可以操作里面的public
    HardDisk *h = new AHardDisk;       //h指向 AHardDisk,相当于可以操作里面的public
    Computer *com = new Computer(h,c);  //将两个指针传给 m_h, m_c, 他们自然可以操作work();
    com->work();
    
    return 0;
}
3、单例模式-懒汉式

单例模式:保证一个类只生成唯一的实例对象,也就是说,整个程序空间中,只存在一个实例对象。

#include 
#include 
#include 
using namespace std;


class Singleton
{
    private:
        static Singleton *m_instance;
        static int count;
        Singleton()
        {

        }
    public:
        static Singleton *GetInstance()
        {
            if (NULL == m_instance)
            {
                printf("分配空间n");
                usleep(1000000);
                m_instance = new Singleton;
            }
            count++;
            return m_instance;
            
        }
        static int GetCount()
        {
            return count;
        }
        void Release()
        {
            count--;
            if (count == 0 && m_instance != NULL)
            {
                delete m_instance;
            }
            
        }
};

Singleton * Singleton::m_instance = NULL;
int Singleton::count = 0;

int main(int argc, char const *argv[])
{
    Singleton *s1 = Singleton::GetInstance();
    Singleton *s2 = Singleton::GetInstance();
    Singleton *s3 = Singleton::GetInstance();
    Singleton *s4 = Singleton::GetInstance();

    cout<Release();
    
    
    return 0;
}

加入线程!

#include 
#include 
#include 
pthread_mutex_t mutex;
using namespace std;


class Singleton
{
    private:
        static Singleton *m_instance;
        static int count;
        Singleton()
        {

        }
    public:
        static Singleton *GetInstance()
        {
            if (NULL == m_instance)
            {
                printf("分配空间n");
                usleep(1000000);
                m_instance = new Singleton;
            }
            count++;
            return m_instance;
            
        }
        static int GetCount()
        {
            return count;
        }
        void Release()
        {
            count--;
            if (count == 0 && m_instance != NULL)
            {
                delete m_instance;
            }
            
        }
};

void *CreateInstance(void *arg)
{
    

    pthread_mutex_lock(&mutex);
    Singleton *s = Singleton::GetInstance();
    cout< 
4、单例模式-饿汉式 

先分配空间,在按照单例模式,只分配一次空间。

#include 
#include 
#include 
pthread_mutex_t mutex;
using namespace std;


class Singleton
{
    private:
        static Singleton *m_instance;
        static int count;
        Singleton()
        {

        }
    public:
        static Singleton *GetInstance()
        {
            
            count++;
            return m_instance;
            
        }
        static int GetCount()
        {
            return count;
        }
        void Release()
        {
            count--;
            if (count == 0 && m_instance != NULL)
            {
                delete m_instance;
            }
            
        }
};

Singleton * Singleton::m_instance = new Singleton;  //先分配空间
int Singleton::count = 0;

int main(int argc, char const *argv[])
{
   Singleton *s1 = Singleton::GetInstance();
    Singleton *s2 = Singleton::GetInstance();
    Singleton *s3 = Singleton::GetInstance();
    Singleton *s4 = Singleton::GetInstance();

    cout<Release();
    
    return 0;
}
5、工厂模式 (1)简单工厂模式
#include 
using namespace std;

class Fruit
{
    public:
        virtual void show() = 0;

};

class Apple:public Fruit
{
    public:
        void show()
        {
            cout<<"this is apple....."<CreateApple();
    Fruit->show();
    delete Fruit;

    Fruit = f->CreateBanana();
    Fruit->show();
    delete Fruit;
    
    return 0;
}

(2)工厂模式
#include 
using namespace std;

class Fruit
{
    public:
        virtual void show() = 0;

};

class Apple:public Fruit
{
    public:
        void show()
        {
            cout<<"this is apple....."<Create();
    Fruit->show();
    delete f;
    delete Fruit;

    f = new BananaFactory;
    Fruit = f->Create();
    Fruit->show();
    delete f;
    delete Fruit;
    
    return 0;
}
(3)抽象工厂模式
#include 
using namespace std;

class Fruit
{
    public:
        virtual void show() = 0;

};

class NorthApple:public Fruit
{
    public:
        void show()
        {
            cout<<"this is northapple....."<CreateApple();
    fruit->show();
    delete fruit;

    fruit = f->CreateBanana();
    fruit->show();
    delete fruit;
}

int main(int argc, char const *argv[])
{
    Factory *f = new SouthFactory;
    Create(f);
    delete f;

    f = new NorthFactory;
    Create(f);
    delete f;
    
    return 0;
}
6、建造者模式 (1)简单版
#include 
using namespace std;

class House
{
    private:
        string wall;
        string window;
        string door;
    public:
        void SetWall()
        {
            wall = "WALL";
        }
        void Setwindow()
        {
            window = "WINDOW";
        }
        void Setdoor()
        {
            door = "DOOR";
        }
};

class Builder
{
    private:
        House *house;
    public:
        Builder(House *h)
        {
            house = h;
        }
        void Constructor()
        {
            house->Setdoor();
            house->SetWall();
            house->Setwindow();
        }
};

int main(int argc, char const *argv[])
{
    House *h = new House;
    Builder *b = new Builder(h);
    b->Constructor();
    
    return 0;
}
(2)建造者模式
#include 
using namespace std;

class House
{
    private:
        string wall;
        string window;
        string door;
    public:
        void SetWall(string w)
        {
            wall = w;
        }
        void Setwindow(string w)
        {
            window = w;
        }
        void Setdoor(string d)
        {
            door = d;
        }
};

class Builder
{
    protected:
        House *house;
    public:
        virtual void Constructor() = 0;
};

class CommonBuilder:public Builder
{
    public:
        CommonBuilder(House *h)
        {
            house = h;
        }
        void Constructor()
        {
            house->Setdoor("DOOR");
            house->SetWall("WALL");
            house->Setwindow("WINDOW");
        }
};

class VillaBuilder:public Builder
{
    public:
        VillaBuilder(House *h)
        {
            house = h;
        }
        void Constructor()
        {
            house->Setdoor("VILLADOOR");
            house->SetWall("VILLAWALL");
            house->Setwindow("VILLAWINDOW");
        }
};

class Designer
{
    private:
        Builder *b;
    public:
        void SetBuilder(Builder *builder)
        {
            b = builder;
        }
        void Constructor()
        {
            b->Constructor();
        }
};

int main(int argc, char const *argv[])
{
    Designer *d = new Designer;
    House *h = new House;
    Builder *b = new CommonBuilder(h);
    d->SetBuilder(b);
    d->Constructor();
    delete b;
    
    return 0;
}
7、原型模式
#include 
#include 
using namespace std;

class Person
{
    protected:
        char name[32];
        int age;
    public:
        Person()
        {

        }
        Person(char *n, int a)
        {
            strcpy(name,n);
            age = a;
        }
        virtual void show() = 0;
        virtual Person* clone() = 0;
};

class Student:public Person
{
    private:
        int id;
    public:
        Student()
        {

        }
        Student(char *n, int a, int i):Person(n,a)
        {
            id = i;
        }
        void show()
        {
            cout<<"name = "<#include 
#include 
using namespace std;

class iFile
{
    public:
        virtual string GetName() = 0;
        virtual int Add(iFile *file) = 0;
        virtual int Remove(iFile *file) = 0;
        virtual list *GetChild() = 0;
};

class File:public iFile
{
    private:
        string name;
    public:
        File(string n)
        {
            name = n;
        }
        string GetName()
        {
            return name;
        }
        int Add(iFile *file)
        {
            return -1;
        }
        int Remove(iFile *file)
        {
            return -1;
        }
        list*GetChild()
        {
            return NULL;
        }
};

class Dir : public iFile
{
    private:
        string name;
        list *l;

    public:
        Dir(string n)
        {
            name = n;
            l = new list;
        }
        string GetName()
        {
            return name;
        }
        int Add(iFile *file)
        {
            l->push_back(file);
            return 1;
        }
        int Remove(iFile *file)
        {
            l->remove(file);
            return 1;
        }
        list *GetChild()
        {
            return l;
        }
};

void show(iFile *root, int gap)
{
    for (int i = 0; i < gap; i++)
    {
        cout<<"---";
    }
    if (root != NULL)
    {
        cout<GetName()< *l = root->GetChild();
    if (l != NULL)
    {
        for (auto it = l->begin(); it != l->end(); it++)
        {
            show(*it, gap+1);
        }
        
    }
    
}

int main(int argc, char const *argv[])
{
    iFile *dir1 = new Dir("home");
    iFile *dir2 = new Dir("day1");
    iFile *dir3 = new Dir("day2");

    iFile *file1 = new File("1.c");
    iFile *file2 = new File("2.c");
    iFile *file3 = new File("3.c");
    iFile *file4 = new File("4.c");
    iFile *file5 = new File("5.c");
    iFile *file6 = new File("6.c");

    dir1->Add(file1);
    dir2->Add(file2);
    dir2->Add(file3);
    dir3->Add(file4);
    dir3->Add(file5);
    dir3->Add(file6);
    dir3->Add(file6);

    dir1->Add(dir2);
    dir1->Add(dir3);
    show(dir1,0);

    return 0;
}

9、代理模式
#include 
using namespace std;

class Sale
{
    public:
        virtual void SaleBook() = 0;
};

class BookStore:public Sale
{
    private:
        static int count;
    
    public:
        void SaleBook()
        {
            cout<<"书店卖书"<SaleBook();
        }
};

int main(int argc, char const *argv[])
{
    Sale *store = new BookStore;
    Sale *taoBao = new TaoBao(store);
    store->SaleBook();
    taoBao->SaleBook();
    cout< 
10、装饰模式 

//把要添加的附加功能分别放在单独的类中,让这个类包含有装饰的对象

#include 
using namespace std;

class Phone
{
    public:
        virtual void Function() = 0;
};

class CallPhone:public Phone
{
    public:
        void Function()
        {
            cout<<"能打电话的手机"<Function();
            cout<<"能拍照的手机"<Function();
            cout<<"能听音乐的手机.."<Function();
            cout<<"能上网的手机..."<Function();

    cout<<"***************拍照******************"<Function();

    cout<<"***************听音乐******************"<Function();

    cout<<"***************上网******************"<Function();
    
    return 0;
}
11、适配器模式

//适配器模式:改变已有类或外部类的接口形式

//适用情况:将一个类的接口转成客户所希望的另一个接口

#include 
using namespace std;

class Current
{
    public:
        virtual int GetCurrent() = 0;
};

class Current_220:public Current
{
    public:
        int GetCurrent()
        {
            return 220;
        }
};

class Adapter:public Current
{
    private:
        Current *current;
    
    public:
        Adapter(Current *c)
        {
            current = c;
        }
        int GetCurrent()
        {
            if (current->GetCurrent() == 220)
            {
                return 12;
            }
            else
            {
                return 5;
            }
            
        }
};

class Phone
{
    private:
        Current *current;
    public:
        Phone(Current *c)
        {
            current = c;
        }
        void Start()
        {
            if (current->GetCurrent() == 220)
            {
                cout<<"boom..."<GetCurrent() == 12)
            {
                cout<<"手机充电中......"<Start();
    
    return 0;
}

12、享元模式
#include 
#include 
using namespace std;

class Student
{
    private:
        string name;
        int age;
        int id;

    public:
        Student()
        {

        }
        Student(string n, int a, int i)
        {
            name = n;
            age = a;
            id = i;
        }
        string GetName()
        {
            return name;
        }
        int GetAge()
        {
            return age;
        }
        int GetId()
        {
            return id;
        }
};

class FwFactory
{
    private:
        multimap *m;
    
    public:
        FwFactory()
        {
            m = new multimap;
        }
        ~FwFactory()
        {
            while (!m->empty())
            {
                Student *tmp = m->begin()->second;
                delete tmp;
                m->erase(m->begin());
            }
            delete m;
            
        }
        void GetPerson(int id)
        {
            string name;
            int age;
            multimap::iterator it;
            it = m->find(id);

            if (it == m->end())
            {
                cout<<"input the name age...."<>name>>age;
                Student *s = new Student(name, age, id);
                m->insert(make_pair(id,s));
            }
            else
            {
                Student *s = it->second;
                cout<GetName()<GetAge()<GetId()<GetPerson(1);
    f->GetPerson(2);
    f->GetPerson(3);
    cout<<"*******************"<GetPerson(3);
    
    return 0;
}
13、观察者模式

//当一个对象状态发生变化时,自动通知其它关联对象,自动解析对象状态

#include 
#include 
using namespace std;

class Infom;
class Observer  //观察者
{
    public:
        virtual void Subscribe(Infom *l) = 0;   //订阅
        virtual void Unsubscribe(Infom *l) = 0;   //取消订阅
        virtual void Update(string str) = 0;   //更新状态
};

class Infom  //通知者    秘书
{
    public:
        virtual void Add(Observer *o) = 0;
        virtual void Remove(Observer *o) = 0;
        virtual void Noftify(string str) = 0;
};

class secretary:public Infom
{
    private:
        list l;
    
    public:
        virtual void Add(Observer *o)
        {
            l.push_back(o);
        }
        virtual void Remove(Observer *o)
        {
            l.remove(o);
        }
        virtual void Noftify(string str)
        {
            for (auto it = l.begin(); it != l.end(); it++)
            {
                (*it)->Update(str);
            }
            
        }
};

class Staff:public Observer
{
    public:
        virtual void Subscribe(Infom *l)    //订阅
        {
            l->Add(this);
        }
        virtual void Unsubscribe(Infom *l)  //取消订阅
        {
            l->Remove(this);
        }
        virtual void Update(string str)   //更新状态
        {
            if (str == "WARNING")
            {
                cout<<"boss is coming"<Subscribe(i);
    o2->Subscribe(i);
    o3->Subscribe(i);
    o4->Subscribe(i);
    i->Noftify("WARNING");
    
    return 0;
}
14、桥接模式
#include 
using namespace std;

class Phone
{
    public:
        virtual void func() = 0;
};

class HUAWEL:public Phone
{
    public:
        void func()
        {
            cout<<"this is HUAWEI..."<func();
            cout<<"this is QQ...."<func();
            cout<<"this is Vchat...."<func();
    
    return 0;
}
15、外观模式
#include 
using namespace std;

class SystemA
{
    public:
        void func()
        {
            cout<<"this is A..."<func();
            b->func();
            c->func();
        }
        
};

int main(int argc, char const *argv[])
{
    Facade *f = new Facade;
    f->func();

    return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/961034.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号