SlideShare una empresa de Scribd logo
1 de 26
Introduction to MVC for Desktop Application Course C1001 He Shiming2010-9
MVC in Windows Desktop Application with Cross-Platform Consideration ideal desktop application development
Obviously: MFC is not a good architecture/standard Most likely, there isn’t such an ideal architecture, like the Rails framework, or even something close to Cocoa Windows API and C++ isn’t helping that much on architecture of products The hard work has to be done by ourselves
Revised MVC Architecture for Us Data Controller View Model
Revised MVC Architecture for Us Model represents information, an underlying file format, database connections and queries View represents user interface, the window and displayed content designed by application logic Controller is the action processor, responding to command sent from views, pick the right model to process it, and update views to reflect action result
An Example, Redesigning Notepad
An Example, Redesigning Notepad Frame is the same (this is the root view):class CMainFrame:  public CFrameWindowImpl<CMainFrame>{public:CEditm_edit; BEGIN_MSG_MAP(CMainFrame)    MESSAGE_HANDLER(WM_CREATE, OnCreate)MESSAGE_HANDLER(WM_SIZE, OnSize)    COMMAND_ID_HANDLER(ID_FILE_NEW, OnFileNew)    COMMAND_ID_HANDLER(ID_FILE_OPEN, OnFileOpen)    COMMAND_ID_HANDLER(ID_FILE_SAVE, OnFileSave)END_MSG_MAP()...
An Example, Redesigning Notepad WM_CREATE handling is the same (still a part of view):LRESULT CMainFrame::OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled){m_edit.CreateWindow(m_hWnd, WS_CHILD|WS_VISIBLE|... WM_SIZE too (another part of view)LRESULT CMainFrame::OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled){  RECT rc_client;GetClientRect(&rc_client);m_edit.SetWindowPos(NULL, &rc_client...
An Example, Redesigning Notepad Before we go further, we research and design this application, in other words, we’ll decide what controller does and what model does
An Example, Redesigning Notepad We knew that Notepad should be able to process text files, so we should have a TextFile class that handles reading and writing, this would be a single threaded, static class whose only job is to accept a file name, and return std::wstringto us (this is a model)
An Example, Redesigning Notepad So we have:class TextFile{public:  static boolReadFile(constwchar_t* filename, std::wstring& content_out);  static boolWriteFile(constwchar_t* filename,constwchar_t* content_in);};
An Example, Redesigning Notepad We knew that user may issue command such as OpenFile, SaveFile, NewFile, so we design a FileController class that has these methods Additionally, this controller should have a buffer that maintains the current displayed text for editing (for use with views), thus we should have methods such as SetContent, and GetContent To deal with large files and potential slowness in networked opening, we may need to make OpenFile, SaveFileasynchronized, therefore we may need a method named IsLastFileOpCompleted for views to decide when toretrieve content (this is a controller)
An Example, Redesigning Notepad So we have:class FileController{public:boolOpenFile(constwchar_t* filename);boolSaveFile(constwchar_t* filename);boolNewFile();boolSetContent(constwchar_t* content);wchar_t* GetContent();boolIsLastFileOpComplete();private:std::wstringm_buffer;  // boost::shared_ptr<boost::thread> m_fileop_thread;  // boost::mutexm_buffer_mutex;};
An Example, Redesigning Notepad What about views?LRESULT CMainFrame::OnFileOpen(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled){CFileDialogfd(TRUE, NULL, NULL, OFN_EXPLORER, L”*.txt”, m_hWnd);  if (!fd.DoModal(m_hWnd))    return 0;  if (!m_view.m_filecontroller.OpenFile(fd.m_szFileName))  {MessageBox(L”There is a problem with file opening”);    return 0;  }SetTimer(TIMER_CHECKFILEOPENCOMPLETE, 50);  // in WM_TIMER, we check m_filecontroller.IsFileOpComplete()  // to decide whether to refresh the m_view using the content  // retrieved via m_filecontroller.GetContent...
An Example, Redesigning Notepad We used timed polling to make sure our controller doesn’t know any details about views, and is thus directly portable Of course timed polling is bad, it consumes and wastes extra resources while checking for return values, due to the stupidity in its design But it can be easily controlled, when it’s required to cancel such a file operation, you kill the timer, and tell the controller to stop file operation
An Example, Redesigning Notepad Timed Polling (Timer) versus Mediator/Observer (Java Callback) versus Delegates (C# Callback) Observer pattern should be used in strict sense *MVC is macro-architecture and design pattern is micro-architecture
An Example, Redesigning Notepad Applying Observer pattern:class IFileObserver{public:  virtual void SetFileOpComplete(booliscomplete) = 0;};class FileObserver:  public IFileObserver{public:  void SetReceiveWindow(HWND hwnd)  {m_hwnd_receive = hwnd;  }  virtual void SetFileOpComplete(booliscomplete)  {    // call SetWindowText depending on |iscomplete|...
An Example, Redesigning Notepad Applying Observer pattern:class FileController{public:  void AttachObserver(IFileObserver* observer);  void DetachObserver();...void _OpenFile_WorkerThread(constwchar_t* filename, bool& ret)  {    // after file read successm_observer->SetFileOpComplete(true);  }...
An Example, Redesigning Notepad To implement multi-tabbing, we put FileController inside CEdit, and replicate CEdit (via std::vector<CEdit>) so that each instance has a controller, a TabController might also be needed to manage tabs To implement syntax highlight, we implement HiliteNode (base model), HiliteParser (model) that translates wchar_t* string into std::vector<HiliteNode>, and make sure our FileController can output stuff returned by HiliteParser, then subclass CEdit to implement actual painting For unicode BOM, only need to revise TextFile class
Redesigning Notepad, What We’ve Achieved: Complete isolation of UI and application logic Complete isolation of application logic and low-level data formats Possible for independent development for most components Possible to run unit-test for each components, so that product quality can be assured Possible to easily port to other platforms Clear application logic for future reference Reusable components for future projects
Arch. Ver. of Notepad v.s. No-arch. Ver. Primary technical difference is class design, class relation, class difference Underlying logic, including frame window management, low-level file reading/writing are mostly the same
When Portability is Our Concern: Remember Cocoa/Objective-C is compatible with C++ Establish user interface on Cocoa framework like before, the equivalent view on Windows cannot be used Bind Cocoa’s interface controller actions to our real portable controllers Only controllers and models can be 100% portable
Architecture and MVC is Mostly About: Class design
Recommended Readings
References Regarding Design Patterns http://stackoverflow.com/questions/516411/raw-function-pointer-from-a-bound-method/516537 http://stackoverflow.com/questions/946834/is-there-a-design-pattern-that-deals-with-callback-mechanism
References Regarding MVC and Others http://en.wikipedia.org/wiki/Model–View–Controller http://www.oracle.com/technetwork/articles/javase/mvc-136693.html http://www.djangoproject.com/ http://code.google.com/webtoolkit/

Más contenido relacionado

La actualidad más candente

Webportal document
Webportal documentWebportal document
Webportal document
Sumit Sahu
 
ASP.NET MVC Introduction
ASP.NET MVC IntroductionASP.NET MVC Introduction
ASP.NET MVC Introduction
Sumit Chhabra
 
M6 l7-java script-handout
M6 l7-java script-handoutM6 l7-java script-handout
M6 l7-java script-handout
Nolboo Kim
 

La actualidad más candente (20)

ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
 
Introduction to angular js for .net developers
Introduction to angular js  for .net developersIntroduction to angular js  for .net developers
Introduction to angular js for .net developers
 
Asp 1a-aspnetmvc
Asp 1a-aspnetmvcAsp 1a-aspnetmvc
Asp 1a-aspnetmvc
 
Asp net-mvc-3 tier
Asp net-mvc-3 tierAsp net-mvc-3 tier
Asp net-mvc-3 tier
 
Angular 2 binding
Angular 2  bindingAngular 2  binding
Angular 2 binding
 
Webportal document
Webportal documentWebportal document
Webportal document
 
Principles of MVC for PHP Developers
Principles of MVC for PHP DevelopersPrinciples of MVC for PHP Developers
Principles of MVC for PHP Developers
 
Difference between asp.net web api and asp.net mvc
Difference between asp.net web api and asp.net mvcDifference between asp.net web api and asp.net mvc
Difference between asp.net web api and asp.net mvc
 
Next generation of frontend architectures - Luca Mezzalira - Codemotion Milan...
Next generation of frontend architectures - Luca Mezzalira - Codemotion Milan...Next generation of frontend architectures - Luca Mezzalira - Codemotion Milan...
Next generation of frontend architectures - Luca Mezzalira - Codemotion Milan...
 
ASp.net Mvc 5
ASp.net Mvc 5ASp.net Mvc 5
ASp.net Mvc 5
 
Introduction to Angular Js
Introduction to Angular JsIntroduction to Angular Js
Introduction to Angular Js
 
Future ASP.NET features for UID / HTML developers
Future ASP.NET features for UID / HTML developersFuture ASP.NET features for UID / HTML developers
Future ASP.NET features for UID / HTML developers
 
Overview of React.JS - Internship Presentation - Week 5
Overview of React.JS - Internship Presentation - Week 5Overview of React.JS - Internship Presentation - Week 5
Overview of React.JS - Internship Presentation - Week 5
 
ASP.NET MVC Introduction
ASP.NET MVC IntroductionASP.NET MVC Introduction
ASP.NET MVC Introduction
 
M6 l7-java script-handout
M6 l7-java script-handoutM6 l7-java script-handout
M6 l7-java script-handout
 
Depurando VBScript no InduSoft Web Studio
Depurando VBScript no InduSoft Web StudioDepurando VBScript no InduSoft Web Studio
Depurando VBScript no InduSoft Web Studio
 
Asp.net c# MVC-5 Training-Day-1 of Day-9
Asp.net c# MVC-5 Training-Day-1 of Day-9Asp.net c# MVC-5 Training-Day-1 of Day-9
Asp.net c# MVC-5 Training-Day-1 of Day-9
 
제 4회 DGMIT R&D 컨퍼런스 : Making a JavaScript based Application in Mac OS X
제 4회 DGMIT R&D 컨퍼런스 : Making a JavaScript based Application in Mac OS X제 4회 DGMIT R&D 컨퍼런스 : Making a JavaScript based Application in Mac OS X
제 4회 DGMIT R&D 컨퍼런스 : Making a JavaScript based Application in Mac OS X
 
Angular from Scratch
Angular from ScratchAngular from Scratch
Angular from Scratch
 
Angular js getting started
Angular js getting startedAngular js getting started
Angular js getting started
 

Destacado

Destacado (9)

Cross-platform Desktop application with AngularJS and build with Node-webkit
Cross-platform Desktop application with AngularJS and build with Node-webkitCross-platform Desktop application with AngularJS and build with Node-webkit
Cross-platform Desktop application with AngularJS and build with Node-webkit
 
Make GUI Apps with Shoes
Make GUI Apps with ShoesMake GUI Apps with Shoes
Make GUI Apps with Shoes
 
An introduction to the ruby ecosystem
An introduction to the ruby ecosystemAn introduction to the ruby ecosystem
An introduction to the ruby ecosystem
 
Developing cross platform desktop application with Ruby
Developing cross platform desktop application with RubyDeveloping cross platform desktop application with Ruby
Developing cross platform desktop application with Ruby
 
Software Requirements Specification for restaurant management system
Software Requirements Specification for restaurant management systemSoftware Requirements Specification for restaurant management system
Software Requirements Specification for restaurant management system
 
Software Requirement Specification
Software Requirement SpecificationSoftware Requirement Specification
Software Requirement Specification
 
Project Plan And Srs Final
Project Plan And Srs FinalProject Plan And Srs Final
Project Plan And Srs Final
 
SRS for student database management system
SRS for student database management systemSRS for student database management system
SRS for student database management system
 
Software Requirement Specification
Software Requirement SpecificationSoftware Requirement Specification
Software Requirement Specification
 

Similar a MVC for Desktop Application - Part 4

Generic Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkGeneric Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity Framework
Akhil Mittal
 
Learning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFrameworkLearning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFramework
Akhil Mittal
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
Akhil Mittal
 
MVC Application using EntityFramework Code-First approach Part4
MVC Application using EntityFramework Code-First approach Part4MVC Application using EntityFramework Code-First approach Part4
MVC Application using EntityFramework Code-First approach Part4
Akhil Mittal
 
A generic log analyzer for auto recovery of container orchestration system
A generic log analyzer for auto recovery of container orchestration systemA generic log analyzer for auto recovery of container orchestration system
A generic log analyzer for auto recovery of container orchestration system
Conference Papers
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
mwillmer
 

Similar a MVC for Desktop Application - Part 4 (20)

Generic Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkGeneric Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity Framework
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
 
Test
TestTest
Test
 
ASP.NET MVC3 RAD
ASP.NET MVC3 RADASP.NET MVC3 RAD
ASP.NET MVC3 RAD
 
Learning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFrameworkLearning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFramework
 
Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
 
The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84The Ring programming language version 1.2 book - Part 5 of 84
The Ring programming language version 1.2 book - Part 5 of 84
 
MVC Application using EntityFramework Code-First approach Part4
MVC Application using EntityFramework Code-First approach Part4MVC Application using EntityFramework Code-First approach Part4
MVC Application using EntityFramework Code-First approach Part4
 
Asp.net c# MVC-5 Training-Day-2 of Day-9
Asp.net c# MVC-5 Training-Day-2 of Day-9Asp.net c# MVC-5 Training-Day-2 of Day-9
Asp.net c# MVC-5 Training-Day-2 of Day-9
 
Asp.net mvc
Asp.net mvcAsp.net mvc
Asp.net mvc
 
Resolve dependency of dependencies using Inversion of Control and dependency ...
Resolve dependency of dependencies using Inversion of Control and dependency ...Resolve dependency of dependencies using Inversion of Control and dependency ...
Resolve dependency of dependencies using Inversion of Control and dependency ...
 
Dot net interview questions and asnwers
Dot net interview questions and asnwersDot net interview questions and asnwers
Dot net interview questions and asnwers
 
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
 
A generic log analyzer for auto recovery of container orchestration system
A generic log analyzer for auto recovery of container orchestration systemA generic log analyzer for auto recovery of container orchestration system
A generic log analyzer for auto recovery of container orchestration system
 
C#.net, C Sharp.Net Online Training Course Content
C#.net, C Sharp.Net Online Training Course ContentC#.net, C Sharp.Net Online Training Course Content
C#.net, C Sharp.Net Online Training Course Content
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
 
Creating web form
Creating web formCreating web form
Creating web form
 
Creating web form
Creating web formCreating web form
Creating web form
 
react-en.pdf
react-en.pdfreact-en.pdf
react-en.pdf
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Último (20)

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 

MVC for Desktop Application - Part 4

  • 1. Introduction to MVC for Desktop Application Course C1001 He Shiming2010-9
  • 2. MVC in Windows Desktop Application with Cross-Platform Consideration ideal desktop application development
  • 3. Obviously: MFC is not a good architecture/standard Most likely, there isn’t such an ideal architecture, like the Rails framework, or even something close to Cocoa Windows API and C++ isn’t helping that much on architecture of products The hard work has to be done by ourselves
  • 4. Revised MVC Architecture for Us Data Controller View Model
  • 5. Revised MVC Architecture for Us Model represents information, an underlying file format, database connections and queries View represents user interface, the window and displayed content designed by application logic Controller is the action processor, responding to command sent from views, pick the right model to process it, and update views to reflect action result
  • 7. An Example, Redesigning Notepad Frame is the same (this is the root view):class CMainFrame: public CFrameWindowImpl<CMainFrame>{public:CEditm_edit; BEGIN_MSG_MAP(CMainFrame) MESSAGE_HANDLER(WM_CREATE, OnCreate)MESSAGE_HANDLER(WM_SIZE, OnSize) COMMAND_ID_HANDLER(ID_FILE_NEW, OnFileNew) COMMAND_ID_HANDLER(ID_FILE_OPEN, OnFileOpen) COMMAND_ID_HANDLER(ID_FILE_SAVE, OnFileSave)END_MSG_MAP()...
  • 8. An Example, Redesigning Notepad WM_CREATE handling is the same (still a part of view):LRESULT CMainFrame::OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled){m_edit.CreateWindow(m_hWnd, WS_CHILD|WS_VISIBLE|... WM_SIZE too (another part of view)LRESULT CMainFrame::OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled){ RECT rc_client;GetClientRect(&rc_client);m_edit.SetWindowPos(NULL, &rc_client...
  • 9. An Example, Redesigning Notepad Before we go further, we research and design this application, in other words, we’ll decide what controller does and what model does
  • 10. An Example, Redesigning Notepad We knew that Notepad should be able to process text files, so we should have a TextFile class that handles reading and writing, this would be a single threaded, static class whose only job is to accept a file name, and return std::wstringto us (this is a model)
  • 11. An Example, Redesigning Notepad So we have:class TextFile{public: static boolReadFile(constwchar_t* filename, std::wstring& content_out); static boolWriteFile(constwchar_t* filename,constwchar_t* content_in);};
  • 12. An Example, Redesigning Notepad We knew that user may issue command such as OpenFile, SaveFile, NewFile, so we design a FileController class that has these methods Additionally, this controller should have a buffer that maintains the current displayed text for editing (for use with views), thus we should have methods such as SetContent, and GetContent To deal with large files and potential slowness in networked opening, we may need to make OpenFile, SaveFileasynchronized, therefore we may need a method named IsLastFileOpCompleted for views to decide when toretrieve content (this is a controller)
  • 13. An Example, Redesigning Notepad So we have:class FileController{public:boolOpenFile(constwchar_t* filename);boolSaveFile(constwchar_t* filename);boolNewFile();boolSetContent(constwchar_t* content);wchar_t* GetContent();boolIsLastFileOpComplete();private:std::wstringm_buffer; // boost::shared_ptr<boost::thread> m_fileop_thread; // boost::mutexm_buffer_mutex;};
  • 14. An Example, Redesigning Notepad What about views?LRESULT CMainFrame::OnFileOpen(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled){CFileDialogfd(TRUE, NULL, NULL, OFN_EXPLORER, L”*.txt”, m_hWnd); if (!fd.DoModal(m_hWnd)) return 0; if (!m_view.m_filecontroller.OpenFile(fd.m_szFileName)) {MessageBox(L”There is a problem with file opening”); return 0; }SetTimer(TIMER_CHECKFILEOPENCOMPLETE, 50); // in WM_TIMER, we check m_filecontroller.IsFileOpComplete() // to decide whether to refresh the m_view using the content // retrieved via m_filecontroller.GetContent...
  • 15. An Example, Redesigning Notepad We used timed polling to make sure our controller doesn’t know any details about views, and is thus directly portable Of course timed polling is bad, it consumes and wastes extra resources while checking for return values, due to the stupidity in its design But it can be easily controlled, when it’s required to cancel such a file operation, you kill the timer, and tell the controller to stop file operation
  • 16. An Example, Redesigning Notepad Timed Polling (Timer) versus Mediator/Observer (Java Callback) versus Delegates (C# Callback) Observer pattern should be used in strict sense *MVC is macro-architecture and design pattern is micro-architecture
  • 17. An Example, Redesigning Notepad Applying Observer pattern:class IFileObserver{public: virtual void SetFileOpComplete(booliscomplete) = 0;};class FileObserver: public IFileObserver{public: void SetReceiveWindow(HWND hwnd) {m_hwnd_receive = hwnd; } virtual void SetFileOpComplete(booliscomplete) { // call SetWindowText depending on |iscomplete|...
  • 18. An Example, Redesigning Notepad Applying Observer pattern:class FileController{public: void AttachObserver(IFileObserver* observer); void DetachObserver();...void _OpenFile_WorkerThread(constwchar_t* filename, bool& ret) { // after file read successm_observer->SetFileOpComplete(true); }...
  • 19. An Example, Redesigning Notepad To implement multi-tabbing, we put FileController inside CEdit, and replicate CEdit (via std::vector<CEdit>) so that each instance has a controller, a TabController might also be needed to manage tabs To implement syntax highlight, we implement HiliteNode (base model), HiliteParser (model) that translates wchar_t* string into std::vector<HiliteNode>, and make sure our FileController can output stuff returned by HiliteParser, then subclass CEdit to implement actual painting For unicode BOM, only need to revise TextFile class
  • 20. Redesigning Notepad, What We’ve Achieved: Complete isolation of UI and application logic Complete isolation of application logic and low-level data formats Possible for independent development for most components Possible to run unit-test for each components, so that product quality can be assured Possible to easily port to other platforms Clear application logic for future reference Reusable components for future projects
  • 21. Arch. Ver. of Notepad v.s. No-arch. Ver. Primary technical difference is class design, class relation, class difference Underlying logic, including frame window management, low-level file reading/writing are mostly the same
  • 22. When Portability is Our Concern: Remember Cocoa/Objective-C is compatible with C++ Establish user interface on Cocoa framework like before, the equivalent view on Windows cannot be used Bind Cocoa’s interface controller actions to our real portable controllers Only controllers and models can be 100% portable
  • 23. Architecture and MVC is Mostly About: Class design
  • 25. References Regarding Design Patterns http://stackoverflow.com/questions/516411/raw-function-pointer-from-a-bound-method/516537 http://stackoverflow.com/questions/946834/is-there-a-design-pattern-that-deals-with-callback-mechanism
  • 26. References Regarding MVC and Others http://en.wikipedia.org/wiki/Model–View–Controller http://www.oracle.com/technetwork/articles/javase/mvc-136693.html http://www.djangoproject.com/ http://code.google.com/webtoolkit/

Notas del editor

  1. Search “C++ Interface” to learn more about interface classes