Browse Source

加入观察者模式

Micooz 9 years ago
parent
commit
1e66d6dc3d

+ 6 - 0
DesignPattern.sln

@@ -33,6 +33,8 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "StrategyPattern", "Strategy
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "StatePattern", "StatePattern\StatePattern.vcxproj", "{41488E20-770F-4E52-9402-A20E1029B56C}"
 EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ObserverPattern", "ObserverPattern\ObserverPattern.vcxproj", "{052C8FBE-6E06-4869-B779-B5AF6D5AEC65}"
+EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
 		Debug|Win32 = Debug|Win32
@@ -99,6 +101,10 @@ Global
 		{41488E20-770F-4E52-9402-A20E1029B56C}.Debug|Win32.Build.0 = Debug|Win32
 		{41488E20-770F-4E52-9402-A20E1029B56C}.Release|Win32.ActiveCfg = Release|Win32
 		{41488E20-770F-4E52-9402-A20E1029B56C}.Release|Win32.Build.0 = Release|Win32
+		{052C8FBE-6E06-4869-B779-B5AF6D5AEC65}.Debug|Win32.ActiveCfg = Debug|Win32
+		{052C8FBE-6E06-4869-B779-B5AF6D5AEC65}.Debug|Win32.Build.0 = Debug|Win32
+		{052C8FBE-6E06-4869-B779-B5AF6D5AEC65}.Release|Win32.ActiveCfg = Release|Win32
+		{052C8FBE-6E06-4869-B779-B5AF6D5AEC65}.Release|Win32.Build.0 = Release|Win32
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
 		HideSolutionNode = FALSE

BIN
DesignPattern.v12.suo


+ 31 - 0
ObserverPattern/Observer.cpp

@@ -0,0 +1,31 @@
+#include "Observer.h"
+#include "Subject.h"
+
+Observer::~Observer() { }
+
+Observer::Observer() { }
+
+Subject* ConcreteObserver::GetSubject() {
+    return _sub;
+}
+
+ConcreteObserver::ConcreteObserver(Subject* sub) {
+    _sub = sub;
+    _sub->Attach(this);
+}
+
+ConcreteObserver::~ConcreteObserver() {
+    _sub->Detach(this);
+    //if (_sub != nullptr) {
+    //    delete _sub;
+    //}
+}
+
+void ConcreteObserver::Update(Subject* sub) {
+    _st = sub->GetState();
+    PrintInfo();
+}
+
+void ConcreteObserver::PrintInfo() {
+    cout << "ConcreteObserver::PrintInfo\t" << _sub->GetState() << endl;
+}

+ 35 - 0
ObserverPattern/Observer.h

@@ -0,0 +1,35 @@
+#ifndef OBSERVER_H
+#define OBSERVER_H
+
+#include <iostream>
+#include <string>
+#include "Subject.h"
+using namespace std;
+
+class Observer {
+public:
+    virtual void Update(Subject* sub) = 0;
+    virtual void PrintInfo() = 0;
+    virtual ~Observer();
+protected:
+    Observer();
+    string _st;
+};
+
+class ConcreteObserver :public Observer {
+public:
+    virtual Subject* GetSubject();
+
+    ConcreteObserver(Subject* sub);
+
+    ~ConcreteObserver();
+
+    void Update(Subject* sub);
+
+    void PrintInfo();
+
+private:
+    Subject *_sub;
+};
+
+#endif //OBSERVER_H

+ 19 - 0
ObserverPattern/ObserverPattern.cpp

@@ -0,0 +1,19 @@
+#include "Subject.h"
+#include "Observer.h"
+
+int main() {
+    Subject *sub = new ConcreteSubject();
+    Observer *o1 = new ConcreteObserver(sub);
+    Observer *o2 = new ConcreteObserver(sub);
+
+    sub->SetState("old");
+    sub->Notify();
+    sub->SetState("new");
+    sub->Notify();
+
+    delete o1;
+    delete o2;
+    delete sub;
+
+    return 0;
+}

+ 90 - 0
ObserverPattern/ObserverPattern.vcxproj

@@ -0,0 +1,90 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{052C8FBE-6E06-4869-B779-B5AF6D5AEC65}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>ObserverPattern</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <PlatformToolset>v120</PlatformToolset>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <PlatformToolset>v120</PlatformToolset>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <LinkIncremental>true</LinkIncremental>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <LinkIncremental>false</LinkIncremental>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <Optimization>MaxSpeed</Optimization>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="Observer.cpp" />
+    <ClCompile Include="ObserverPattern.cpp" />
+    <ClCompile Include="Subject.cpp" />
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="Observer.h" />
+    <ClInclude Include="Subject.h" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>

+ 36 - 0
ObserverPattern/ObserverPattern.vcxproj.filters

@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="源文件">
+      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="头文件">
+      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
+      <Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+    <Filter Include="资源文件">
+      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
+      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="ObserverPattern.cpp">
+      <Filter>源文件</Filter>
+    </ClCompile>
+    <ClCompile Include="Observer.cpp">
+      <Filter>源文件</Filter>
+    </ClCompile>
+    <ClCompile Include="Subject.cpp">
+      <Filter>源文件</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="Observer.h">
+      <Filter>源文件</Filter>
+    </ClInclude>
+    <ClInclude Include="Subject.h">
+      <Filter>源文件</Filter>
+    </ClInclude>
+  </ItemGroup>
+</Project>

+ 32 - 0
ObserverPattern/Subject.cpp

@@ -0,0 +1,32 @@
+#include "Observer.h"
+#include "Subject.h"
+
+void Subject::Attach(Observer* obv) {
+    _obvs.push_front(obv);
+}
+
+void Subject::Detach(Observer* obv) {
+    if (obv != nullptr) {
+        _obvs.remove(obv);
+    }
+}
+
+void Subject::Notify() {
+    for (auto obv : _obvs) {
+        obv->Update(this);
+    }
+}
+
+Subject::~Subject() { }
+
+Subject::Subject() { 
+    //_obvs.clear();
+}
+
+string ConcreteSubject::GetState() {
+    return _st;
+}
+
+void ConcreteSubject::SetState(const string& st) {
+    _st = st;
+}

+ 39 - 0
ObserverPattern/Subject.h

@@ -0,0 +1,39 @@
+#ifndef SUBJECT_H
+#define SUBJECT_H
+
+#include <iostream>
+#include <list>
+#include <string>
+
+class Observer;
+
+using namespace std;
+
+class Subject {
+public:
+    virtual void SetState(const string& st) = 0;
+    virtual string GetState() = 0;
+
+    virtual void Attach(Observer* obv);
+
+    virtual void Detach(Observer* obv);
+
+    virtual void Notify();
+
+    virtual ~Subject();
+protected:
+    Subject();
+private:
+    list<Observer*> _obvs;
+};
+
+class ConcreteSubject :public Subject {
+public:
+    string GetState();
+
+    void SetState(const string& st);
+private:
+    string _st;
+};
+
+#endif// SUBJECT_H