1. 程式人生 > >C++之設計模式原則

C++之設計模式原則

設計模式原則:(1)開放封閉原則:類的改動是通過增加程式碼完成,而不是修改程式碼
#include <iostream>

using namespce std;

class BankWorker
{
	public:
	virtual void show() = 0;       //預留一個介面,用於其他類繼承並實現功能
};

class GetMoney : public BankWorker
{
	public:
	void show()
	{
		cout << "GetMoney !" << endl;
	}
};	


class SaveMoney : public BankWorker
{
	public:
	void show()
	{
		cout << "SaveMoney !" << endl;
	}
};

//此時若需增加功能,則增加子類繼承於基類,無需修改已有程式碼
class TransformMoney : public BankWorker
{
	public:
	void show()
	{
		cout << "TransformMoney !" << endl;
	}
};

int main()
{
	BankWorker *b = new SaveMoney;//定義指標物件
	b->show();
	delete b;     //及時釋放
	
	b = new GetMoney;
	b->show();
	delete b;
	
	b = new TransformMoney;
	b->show();
	delete	b;
	
	return 0;
}
(2)依賴倒置原則:依賴於抽象(介面),不要依賴於具體的實現(類),也就是針對介面程式設計
#include <iostream>

using namespace std;

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

class InterCPU : public CPU
{
    public:
        void cpu_work()
        {
            cout << "cpu_work !" << endl;
        }
};

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

class AHardDisk : public HardDisk
{
    public:
        void harddisk_work()
        {
            cout << "harddisk_work !" << endl;
        }
};

class Computer
{
    private:
        CPU *m_cpu;
        HardDisk * m_harddisk;
    public:
        Computer(CPU *cpu,HardDisk *harddisk)    //建構函式初始化
        {
            m_cpu = cpu;
            m_harddisk = harddisk;
        }
        void show()
        {
            m_cpu->cpu_work();         //多型
            m_harddisk->harddisk_work();
        }
};
int main()
{
    CPU *cpu = new InterCPU;             //修改時可修改此處介面
    HardDisk * harddisk = new AHardDisk;

    Computer *c = new Computer(cpu,harddisk);
    c->show();

    delete c;
    delete cpu;
    delete harddisk;
    
    return 0;
}