工厂方法模式
//创建苹果手机工厂
MobilePhoneFactory mobilePhoneFactoryIphone = new IphoneFactory();
//苹果手机工厂创建手机
MobilePhone mobilePhoneIphone = mobilePhoneFactoryIphone.Create();
//由苹果工厂创建苹果手机
mobilePhoneIphone.print();
//小米工厂生产小米手机
MobilePhoneFactory mobilePhoneFactoryXiaoMi = new XiaoMiFactory();
MobilePhone mobilePhoneXiaoMi = mobilePhoneFactoryXiaoMi.Create();
mobilePhoneXiaoMi.print();
抽象手机类
小米:抽象手机
苹果:抽象手机类
抽象工厂类,解决多系列问题,难以应对对象的变动
小米工厂:抽象工厂 { return new XiaoMi }
苹果工厂:抽象工厂 { return new Iphone }
总结:用户需要什么产品则调用什么工厂,一个具体的工厂只能生产一个具体的产品
// 把一段代码抽象成一个方法
//不用改代码,改配置文件
简单工厂模式
MobilePhone mobilephone1 = MobielPhoneFactory.CreateMobilePhone("苹果");
mobilephone1.print();
MobilePhone mobilephone2 = MobielPhoneFactory.CreateMobilePhone("小米");
mobilephone2.print();
public static MobilePhone CreateMobilePhone(string PhoneBrand)
{
MobilePhone mobilePhone = null;
if (PhoneBrand.Equals("苹果"))
{
mobilePhone = new Iphone();
}
else if (PhoneBrand.Equals("小米"))
{
mobilePhone = new XiaoMI();
}
//生产什么产品依赖传递的参数
//如果有的产品需要生产,这里要增加代码
抽象工厂
**抽象工厂类,解决多系列问题,难以应对对象的变动**
//小米工厂生产小米手机的屏幕和主板
AbstractFactory xiaomiFactory = new XiaoMiFactory();
Screen xiaomiScreen = xiaomiFactory.CreateScreen();
xiaomiScreen.print();
MotherBoard xiaomiMotherBoard = xiaomiFactory.CreateMotherBoard();
xiaomiMotherBoard.print();
//苹果工厂生产苹果手机屏幕和主板
AbstractFactory appleFactory = new AppleFactory();
Screen appleScreen = appleFactory.CreateScreen();
appleScreen.print();
MotherBoard appleMotherBoard = appleFactory.CreateMotherBoard();
appleMotherBoard.print();
生成器模式
**适用范围:隔离出复杂对象的各个部分的变化,同样的构建过程可以创建不同的表示**
**分步骤构建一个复杂的对象,步骤是稳定的,各个部分则频繁变动**
abstract class House{
}
public abstract class Builder{
public abstract void BuildFloor();
public abstract void BuildWall();
public abstract void BuildCeil();
//最后需要构造成房子
public abstract House GetHouse();
}
public class GameManager{
public static House CreateHouse(Builder builder){
builder.BuildFloor();
builder.BuildWall();
builder.BuildCeil();
return builder.GetHouse();
}
}
class APP{
public static void main(){
House house=GameManager.CreateHouse( ChineseHouseBuilder );
}
}
//使用配置文件改写
class App{
public static void main(){
//从配置文件获取程序集名和类名
string assemblyName=ConfigurationSetting("BuilderAssembly");
string builderName=ConfigurationSetting("BuilderClasss");
//加载程序集,获取类型
Assembly assmbly=Assembly.Load(assemblyName);
Type t=assmbly.GetType("builderName");
//实例化构造器
Builder builder=Activator.CreateInstance(t);
//传入参数
House house=GameManager.CreateHouse( builder);
}
}
单例模式之单线程
**不要序列化,不要实现克隆,不适合多线程**
Class Singleton{
private static Singleton instance=null;
private Singleton(){}
public static Singleton Instance{
get{
if(instance==null){
instance=new Singleton();
}
return instance;
}
}
}
单例模式 之多线程
Class Singleton{
private static volatile Singleton instance=null;
private static object lockHelp=new Object();
private Singleton(){}
public static Singleton Instance{
get{
if(instance==null){
lock(lockhelp){
if(instance==null){
instance=new Singleton();
}
}
}
return instance;
}
}
单例模式—多线程简化版
**免费加锁**
Class Singleton{
private static readonly Singleton Instance=new Singleton();
private Singleton(){}
}
//弊端, 使用静态构造器不支持构造传参
**免费加锁**
Class Singleton{
private static readonly Singleton Instance;
static Singleton(){
Instance=new Singleton();
}
private Singleton(){}
}
结构模式之组合模式
目录结构, 套娃
树形结构 表示 “ 部分和整体 ”,用户对单个对象和组合对象的使用具有一致性
**组合模式**
public interface IBox{
void Process();
}
public class SingleBox:IBox{ //叶子节点
void Process(){
//1. Do process for self
// ...
}
//如何处理 Add 和 Remove,可以啥都不干,也可以抛出异常
}
public class ContainerBox:IBox{
ArrayList list=new Arraylist();
//支持添加
public void Add(IBox box){
list.Add(box);
}
//支持移除 TODO
//...
//处理函数
void Process(){
//1. Do process for self
// ...
//2. Do process for the box in the list
if(list!=null){
foreach(IBox box in list){
box.Process(); //这里是一个递归
}
}
}
}
class App{
// 在这里 Add 和 Remove的时候,需要判断 对象是单个对象还是组合对象,改进的方法是
//把 Add 和 Remove 放到接口里面,统一的处理 单个对象和组合对象
}
**外观模式**
使用组合的方式封装子系统,提供统一的外部接口
Facade 模式注重简化接口
//...
Adapter模式, 注重转换接口,对象适配器和类适配器
class Adapter{
Adaptee ; //组合被适配对象
FuncA(){
Adaptee.func();
}
}
Bridge模式 注重分离接口与其实现
//...
Decorator模式 注重稳定接口的前提下 为对象扩展功能
//...
**对象适配器**
namespace 对象适配器
{
class App
{
static void Main(string[] args)
{
ThreeHole threehole = new PowerAdapter();
threehole.Request();
Console.ReadLine();
}
}
/// <summary>
/// 三个孔的插头,也就是适配器模式中的目标(Target)角色
/// </summary>
public class ThreeHole
{
// 客户端需要的方法
public virtual void Request()
{
// ...
}
}
/// <summary>
/// 两个孔的插头,源角色——需要适配的类
/// </summary>
public class TwoHole
{
public void SpecificRequest()
{
Console.WriteLine("我是两个孔的插头");
}
}
/// <summary>
/// 适配器类,这里适配器类没有TwoHole类,
/// 而是引用了TwoHole对象,所以是对象的适配器模式的实现
/// </summary>
public class PowerAdapter : ThreeHole
{
// 引用两个孔插头的实例,从而将客户端与TwoHole联系起来
public TwoHole twoholeAdaptee = new TwoHole();
/// <summary>
/// 实现三个孔插头接口方法
/// </summary>
public override void Request()
{
twoholeAdaptee.SpecificRequest();
}
}
}
**桥接模式**
**装饰模式**
//抽象手机类
public abstract class Phone{
public abstract void Print();
}
//具体的手机类
public class ApplePhone:Phone{
public override void print(){
Console.writeline("....")
}
}
//抽象装饰类
public abstract class Decorator:Phone{
private Phone phone;
public Decorator(phone ph){
this.phone=ph;
}
public override void Print(){
if(phone!=null){
phone.print();
}
}
}
public class Sticker:Decorator{
public Sticker(phone p):base(p){
}
public override void Print(){
base.print();
AddSticker();
}
public void AddSticker(){
Console.WriteLine("添加 贴膜行为")
}
}
public class Accessories:Decorator{
public Accessories(phone p):base(p){
}
public override void print(){
base.print();
AddAccessories();
}
public void AddAccessories(){
Console.WriteLine("")
}
}
class App{
static void Main(string[] args){
Phone ph=new ApplePhone();
Decorator appleWithSticker=new Sticker(ph);
appleWithSticker.print();
}
}
//使用享元模式最大程度的减少实例化类似的对象
//实例的参数移动到享元对象的外面,在方法调用是将他们传递进来
//内部状态:在享元对象的内部并且不会随环境的变化而变化
//外部状态:随环境的改变而改变,不可以共享的状态。
//抽象享元类,提供具体享元类具有的方法
public abstract class FlyWeight{
public abstract void operation(int ext);
}
//具体享元类
public class ConcreteFlyWeight:FlyWeight{
private string inState;
public ConcreteFlyWeight(string inner){
this.inState=inner;
}
public override void operation(int ex){
}
}
//工厂
public class FlyWeightFactory{
public HashTable flyWeights=new HashTable();
public FlyWeightFactory(){
flyWeights.Add("A",new ConcreteFlyWeight("A"));
flyWeights.Add("B",new ConcreteFlyWeight("B"));
flyWeights.Add("C",new ConcreteFlyWeight("C"));
}
public FlyWeight GetFlyWeight(string key){
return flyWeights[key] as FlyWeight;
}
}
class App{
static void Main(string[] arg){
int externState=10;
FlyWeightFactory factory=new FlyWeightFactory();
FlyWeight fa=factory.GetFlyWeight("A");
if(fa!=null){
fa.operation(externState);
}else{
ConcreteFlyWeight d=new ConcreteFlyWeight("D");
factory.FlyWeight.Add("D",d);
}
}
}
**代理模式**
//代理模式
//增加中间层,让代理对象代替目标对象
//抽象主题类,代理主题类,真实主题类
public abstract class Person{
public abstract void Buy();
}
public class RealBuyPerson:Person
{
public override void Buy(){
}
}
public class Friend:Person
{
RealBuyPerson real;
public override void Buy(){
if(real==null){
real=new RealBuyPerson();
}
this.PreBuy();
real.Buy();
this.PostBuy();
}
public void PreBuy(){}
public void PostBuy(){}
}
class App{
static void Main(string[] args){
Person proxy=new Friend();
proxy.Buy();
Console.Read();
}
}
**命令模式**
**对行为进行记录,撤销,重做,事务处理,**
**将一个请求封装为一个对象**
**发出命令和执行命令的责任分开**
class Document{
public void ShotText(){
...
}
}
class Shape{
public void ShowShape(){
...
}
}
class APP_01{
public void Show(){
Document doc=new Document();
doc.ShowText();
Shape sh=new Shape();
sh.ShowShape();
//这种做法不支持撤销,记录
}
}
---------------------------------------------------------
public interface Command{
void Execute();
void Undo();
void Redo();
}
class Document:Command{
public override void Execute(){
//...
}
}
class App_02{
Stack<Command> stack;
public void Show(){
foreach(Commnad com in list){
com.Execute();
}
}
public void Undo(){
if(canUndo){
Command com=Stack.Pop();
com.Undo();
undolist.Add(com);
}
}
public void Redo(){
if(canRedo){
Command com=undoList.pop();
com.Redo();
}
}
}
-------------------------不改变原有的类-----------------------
class DocumentCommand:Command{
Document document;
Public DocumentCommand(Document doc){
this.document=doc;
}
public void Show(){
...
}
public void Undo(){
...
}
public void Redo(){
...
}
}
**命令模式实现**
// 教官,负责调用命令对象执行请求
public class Invoke
{
public Command _command;
public Invoke(Command command)
{
this._command = command;
}
public void ExecuteCommand()
{
_command.Action();
}
}
// 命令抽象类
public abstract class Command
{
// 命令应该知道接收者是谁,所以有Receiver这个成员变量
protected Receiver _receiver;
public Command(Receiver receiver)
{
this._receiver = receiver;
}
// 命令执行方法
public abstract void Action();
}
//
public class ConcreteCommand :Command
{
public ConcreteCommand(Receiver receiver)
: base(receiver)
{
}
public override void Action()
{
// 调用接收的方法,因为执行命令的是学生
_receiver.Run1000Meters();
}
}
// 命令接收者——学生
public class Receiver
{
public void Run1000Meters()
{
Console.WriteLine("跑1000米");
}
}
// 院领导
class Program
{
static void Main(string[] args)
{
// 初始化Receiver、Invoke和Command
Receiver r = new Receiver();
Command c = new ConcreteCommand(r);
Invoke i = new Invoke(c);
// 院领导发出命令
i.ExecuteCommand();
}
}
**解释器模式**
**观察者模式**
**如果在被观察者之间有循环依赖的话,被观察者会触发它们之间进行循环调用,导致系统崩溃,在使用观察者模式应特别注意这点**
**如果一个被观察者有很多直接和间接的观察者时,将所有的观察者都通知到会花费很多时间**
**模板方法模式**
// 客户端调用
class Client
{
static void Main(string[] args)
{
// 创建一个菠菜实例并调用模板方法
Spinach spinach = new Spinach();
spinach.CookVegetabel();
Console.Read();
}
}
public abstract class Vegetabel
{
// 模板方法,不要把模版方法定义为Virtual或abstract方法,避免被子类重写,防止更改流程的执行顺序
public void CookVegetabel()
{
Console.WriteLine("抄蔬菜的一般做法");
this.pourOil();
this.HeatOil();
this.pourVegetable();
this.stir_fry();
}
// 第一步倒油
public void pourOil()
{
Console.WriteLine("倒油");
}
// 把油烧热
public void HeatOil()
{
Console.WriteLine("把油烧热");
}
// 油热了之后倒蔬菜下去,具体哪种蔬菜由子类决定
public abstract void pourVegetable();
// 开发翻炒蔬菜
public void stir_fry()
{
Console.WriteLine("翻炒");
}
}
// 菠菜
public class Spinach : Vegetabel
{
public override void pourVegetable()
{
Console.WriteLine("倒菠菜进锅中");
}
}
// 大白菜
public class ChineseCabbage : Vegetabel
{
public override void pourVegetable()
{
Console.WriteLine("倒大白菜进锅中");
}
}
**中介者模式**
//中介者模式
//定义一个中间对象来封装一系列对象之间的交互关系
//使得各个对象不需要显式的相互引用
//抽象中介者 具体中介者 抽象同事类 具体同事类
public abstract class AbstractMediator
{
protected AbstractCardPartner A;
protected AbstractCardPartner B;
public AbstractMediator(AbstractCardPartner a, AbstractCardPartner b){
A=a;
B=b;
}
public abstract void AWin(int count);
public abstract void BWin(int count);
}
public class MediatorPater:AbstractMediator
{
public MediatorPater(AbstractCardPartner a, AbstractCardPartner b):base(a,b){
}
public override void Awin(int count){
A.MoneyCount+=count;
B.MoneyCount-=count;
}
public override void Bwin(int count){
A.MoneyCount-=count;
B.MoneyCount+=count;
}
}
public abstract class AbstractCardPartner
{
public int MoneyCount{get;set;}
public AbatractCardPartner(){
MoneyCount=0;
}
public abstract void ChangeCount(int count, AbstractMediator mediator);
}
public class ParnterA:AbstractCardPartner
{
public override void ChangeCount(int count, AbstractMediator med){
med.Awin(count);
}
}
public class ParnterB:AbstractCardPartner
{
public override void ChangeCount(int count, AbstractMediator med){
med.Bwin(count);
}
}
class App
{
static void Main(string[] args){
AbstractCardPartner A=new ParnterA();
AbstractCardPartner B=new ParnterB();
A.MoneyCount=20;
B.MoneyCount=20;
AbstractMediator med=new MediatorPater(A,B);
A.ChangeCount(5,med);
B.ChangeCount(10,med);
}
}
**状态模式**