C++11单利模式
class Singleton
{
private:
Singleton();
Singleton(
const Singleton&);
Singleton&
operator = (
const Singleton&);
public:
static Singleton&
GetInstance()
{
static Singleton instance;
return instance;
}
private:
//
class members
};
简单工厂模式
/************************************************************************/
/************************************************************************/
#include
"stdafx.h"
#include <iostream>
using namespace std;
class Product
{
public:
virtual
void show() =
0;
};
class Product_A :
public Product
{
void show()
{
cout <<
"Product_A" << endl;
}
};
class Product_B :
public Product
{
void show()
{
cout <<
"Product_B" << endl;
}
};
class Factory
{
public:
Product*
Create(
int i)
{
switch (i)
{
case 1:
return new Product_A;
break;
case 2:
return new Product_B;
break;
default:
break;
}
}
};
int main()
{
Factory* factory =
new Factory;
factory->Create(
1)->show();
factory->Create(
2)->show();
system(
"pause");
return 0;
}
抽象工厂模式
/************************************************************************/
#include
"stdafx.h"
#include <iostream>
using namespace std;
class Product_1
{
public:
virtual
void show() =
0;
};
class Product_A1 :
public Product_1
{
void show()
{
cout <<
"Product_A1" << endl;
}
};
class Product_B1 :
public Product_1
{
void show()
{
cout <<
"Product_B1" << endl;
}
};
class Product_2
{
public:
virtual
void show() =
0;
};
class Product_A2 :
public Product_2
{
void show()
{
cout <<
"Product_A2" << endl;
}
};
class Product_B2 :
public Product_2
{
void show()
{
cout <<
"Product_B2" << endl;
}
};
class Factory
{
public:
virtual Product_1*
Create1() =
0;
virtual Product_2* Create2() =
0;
};
class Factory_A :
public Factory
{
public:
Product_1*
Create1()
{
return new Product_A1;
}
Product_2* Create2()
{
return new Product_A2;
}
};
class Factory_B :
public Factory
{
public:
Product_1*
Create1()
{
return new Product_B1;
}
Product_2* Create2()
{
return new Product_B2;
}
};
int main()
{
Factory_A* factory_a =
new Factory_A;
factory_a->Create1()->show();
factory_a->Create2()->show();
Factory_B* factory_b =
new Factory_B;
factory_b->Create1()->show();
factory_b->Create2()->show();
system(
"pause");
return 0;
}
工厂方法模式
/************************************************************************/
#include
"stdafx.h"
#include <iostream>
using namespace std;
class Product
{
public:
virtual
void show() =
0;
};
class Product_A :
public Product
{
void show()
{
cout <<
"Product_A" << endl;
}
};
class Product_B :
public Product
{
void show()
{
cout <<
"Product_B" << endl;
}
};
class Factory
{
public:
virtual Product*
Create() =
0;
};
class Factory_A :
public Factory
{
public:
Product*
Create()
{
return new Product_A;
}
};
class Factory_B :
public Factory
{
public:
Product*
Create()
{
return new Product_B;
}
};
int main()
{
Factory_A* factory_a =
new Factory_A;
Factory_B* factory_b =
new Factory_B;
factory_a->Create()->show();
factory_b->Create()->show();
system(
"pause");
return 0;
}