├── Debug ├── cppplaydesignpatterns.exe ├── cppplaydesignpatterns.ilk └── cppplaydesignpatterns.pdb ├── README.md ├── cppplaydesignpatterns.sln ├── cppplaydesignpatterns.v12.suo └── cppplaydesignpatterns ├── Debug ├── abstractfactory.obj ├── adapter.obj ├── adapter1.obj ├── bridge.obj ├── builder.obj ├── chainofresponsibility.obj ├── command1.obj ├── composite.obj ├── composite1.obj ├── cor_broker.obj ├── cor_pointer.obj ├── cppplayd.608DE9D9.tlog │ ├── CL.read.1.tlog │ ├── CL.write.1.tlog │ ├── cl.command.1.tlog │ ├── cppplaydesignpatterns.lastbuildstate │ ├── link.command.1.tlog │ ├── link.read.1.tlog │ └── link.write.1.tlog ├── cppplaydesignpatterns.Build.CppClean.log ├── cppplaydesignpatterns.log ├── decorator.obj ├── decorator1.obj ├── facade.obj ├── factorymethod.obj ├── flyweight.obj ├── interpreter.obj ├── iterator.obj ├── mediator.obj ├── memento.obj ├── observer.obj ├── observerboost.obj ├── prototype.obj ├── singleton.obj ├── state1.obj ├── state2.obj ├── strategy_dynamic.obj ├── template.obj ├── vc120.idb ├── vc120.pdb ├── virtualproxy.obj └── visitor.obj ├── abstractfactory.cpp ├── adapter.cpp ├── adapter1.cpp ├── bridge.cpp ├── builder.cpp ├── chainofresponsibility.cpp ├── command1.cpp ├── composite.cpp ├── composite1.cpp ├── cor_broker.cpp ├── cor_pointer.cpp ├── cppplaydesignpatterns.vcxproj ├── cppplaydesignpatterns.vcxproj.filters ├── cppplaydesignpatterns.vcxproj.user ├── decorator.cpp ├── decorator1.cpp ├── facade.cpp ├── factorymethod.cpp ├── flyweight.cpp ├── headers.h ├── hottechnology.h ├── interpreter.cpp ├── iterator.cpp ├── mediator.cpp ├── memento.cpp ├── observer.cpp ├── observerboost.cpp ├── prototype.cpp ├── singleton.cpp ├── state1.cpp ├── state2.cpp ├── strategy_dynamic.cpp ├── template.cpp ├── virtualproxy.cpp └── visitor.cpp /Debug/cppplaydesignpatterns.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/Debug/cppplaydesignpatterns.exe -------------------------------------------------------------------------------- /Debug/cppplaydesignpatterns.ilk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/Debug/cppplaydesignpatterns.ilk -------------------------------------------------------------------------------- /Debug/cppplaydesignpatterns.pdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/Debug/cppplaydesignpatterns.pdb -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cppplaydesignpatterns 2 | simple modern c++ design patterns 3 | 4 | ingenuity: quality of being clever, original and inventive. apply new ideas to solve problems and meet challenges. 5 | innovation: don't imitate, innovate, challenge conventional thinking, why? why not? think differently ... 6 | 1. clever 7 | 2. original 8 | 3. inventive 9 | 4. new ideas 10 | 5. solve problems 11 | 6. meet challenges 12 | 7. focus on the goal 13 | 14 | push it baby push it ... for all you do this is for you ... rock the house ... 15 | 16 | for these use cases 17 | 1. adapter -> wrap an existing library, provide specific functionality to meet the needs of the consumers of the api [adapter.cpp] 18 | 2. adapternew -> legacy component is not compatible with system that wants to use it. an abstract base class is created that specifies 19 | the desired interface. an adapter class is defined that publicly inherits interface of abstract class and privately inherits 20 | the implementation of the legacy component. the adapter class maps or impedance matches the new interface to the old implementation. In 21 | the constructor of the adapter the transformation takes place [adapter1.cpp] 22 | 3. builder -> object oriented, separate construction of complex object from its representation so that the same construction 23 | process can create different representations [builder.cpp] 24 | 4. composite -> identify scalar/primitive classes and vector container classes. all concrete classes implement an interface, they are 25 | all interchangeable. all concrete classes have is a relationship to interface. all container classes couple themselves to interface. 26 | recursive composition, composite has a set of children up the is a hierarchy. container classes use polymorphism as they delegate to 27 | their children [composite.cpp] 28 | 5. decorator -> extend functionality, decorate or wrap, statically or dynamically without affecting existing behavior [decorator.cpp, decorator1.cpp] 29 | 6. observer -> need to be informed when certain things happen, object's property changes, object does something, some external event happens, listen to events and be notified when they occur. an observer is an object that wishes to be informed when events happen in the system, typically by providing a callback function to call when events occur. the entity generating the events is sometimes called an observable [observer.cpp, observerboost.cpp] 30 | 7. state -> the object's behavior is determined by its state, an object transitions from one state to another(something needs to trigger the transition). a formalized contract which manages states and transitions is called a state machine [state.cpp state1.cpp] 31 | 8. strategy -> enable the exact behavior of a system to be selected at either run-time (dynamic) or compile-time (static), also known as policy. encapsulate an algorithm in class hierarchy, have clients of that algorithm hold a pointer to base class of hierarchy, delegate all requests for that algorithm to the anonymous contained object [strategy.cpp] 32 | 9. template method -> define skeleton of algorithm, concrete implementations in subclasses [template.cpp] 33 | 10. chain of responsibility -> a chain of components who all get a chance to process a command or query, optionally having a default processing implementation and an ability to terminate the processing chain. put a next pointer in base class, chain method in base class always delegates to next object, if derived class cannot handle, delegate to base class [cor_pointer.cpp, cor_broker.cpp] 34 | 11. command -> an object represents an instruction or sequence of instructions to perform a particular action. contains all information required to execute the action. class encapuslates number of following: receiver object, method to invoke, arguments to pass. instantiate an object for each callback, pass each object to its future sender, when sender ready to callback to receiver, execute is invoked [command1.cpp] 35 | 12. interpreter -> given a language define a representation for its grammar along with an interpreter that uses the the representation to interpret sentences in the language, map a domain to a language, language to a grammar, and the grammar to a hierarchical object oriented design. an abstract base class specifies the method interpret, each concrete subclass implements interpret by accepting as an argument the current state state of the language stream and adding its contribution to the problem solving process [interpreter.cpp] 36 | 13. iterator -> abstract traversal of wildly different data structures so that algorithms can be defined that are capable of interfacing with each other transparently. access elements of aggregate object sequentially without exposing underlying representation, decouple collection classes and algorithms, promote to full object status traversal of collection, polymorphic traversal [iterator.cpp] 37 | 14. mediator -> an object encapsulates how a set of objects interact, loose coupling by keeping objects from referring to each other explicitly, vary their interaction independently, design an intermediary to decouple many peers, promote many to many relationships between interacting peers to full object status [mediator.cpp] 38 | 15. memento -> need to restore an object back to its previous state (undo, or rollback), capture and externalize an object's internal state so that the object can be returned to this state later, a magic cookie that encapsulates a checkpoint capability [memento.cpp] 39 | 16. facade -> facade takes a riddle wrapped in enigma shrouded in mystery and interjects a wrapper that tames the amorphous and inscrutable mass of software, provide a unified interface to a set of interfaces in a subsystem, define a higher level interface that makes the subsystem easier to use, wrap a complicated subsystem with a simple interface, the facade should not become an all knowing oracle or god object [facade.cpp] 40 | 17. flyweight -> space optimization technique, use less memory by storing data externally associated with objects, share objects to allow their use at fine granularity without prohibitive cost, each flyweight object consists of two parts, state dependent extrinsic part, state independent intrinsic part, intrinsic state is stored shared in the flyweight object, extrinsic state is stored computed by client objects and passed to flyweight object when invoked [flyweight.cpp] 41 | 18. prototype -> co-opt one instance of a class for use as a breeder of all future instances, specify the kinds of objects to create using a prototypical instance, new operator is considered harmful [prototype.cpp] 42 | 19. proxy -> provide a surrogate or placeholder for another object to control access to it, use an extra level of indirection, to support distributed, controlled, intelligent access, add a wrapper and delegation to protect the real component from undue complexity [virtualproxy.cpp] 43 | 20. factory method -> define an interface for creating an object but let subclasses decide which class to instantiate, factory method lets a class defer instantiation to subclasses, define a virtual constructor, new operator considered harmful [factorymethod.cpp] 44 | 21. singleton -> ensure a class has only one instantiation, provide a global point of access to it, encapsulated "just in time initialization" or "initialization on first use" [singleton.cpp] 45 | 22. bridge -> decouple an abstraction from its implementation, so that the two can vary independently, publish interface in an inheritance hierarchy, bury implementation in its own hierarchy, beyond encapsulation to insulation [bridge.cpp] 46 | 23. visitor -> represent an operation to be performed, on the elements of an object structure, visitor lets you define a new operation without changing the classes of the elements on which it operates, classic technique for recovering lost type information, do the right thing based on the type of two objects, double dispatch [visitor.cpp] 47 | 48 | -------------------------------------------------------------------- 49 | Manifesto for Agile Software Development 50 | We are uncovering better ways of developing software by doing it and helping others do it. Through this work we have come to value: 51 | Individuals and interactions over processes and tools. 52 | Working software over comprehensive documentation. 53 | Customer collaboration over contract negotiation. 54 | Responding to change over following a plan. 55 | While there is value in items on the right we value items on the left more. 56 | 1. Individuals and interactions 57 | 2. Working software ++ 58 | 3. Customer collaboration 59 | 4. Responding to change 60 | 61 | -------------------------------------------------------------------- 62 | Principles behind the Agile Manifesto 63 | We follow these principles: 64 | 1. Our highest priority is to satisfy the customer through early and continuous delivery of valuable software. ++ 65 | 2. Welcoming changing requirements, even late in development. Agile processes harness change for the customers competitive advantage. 66 | 3. Deliver working software frequently, from a couple of weeks to a couple of months, with a preference to the shorter time scale. ++ 67 | 4. Business people and developers must work together daily throughout the project. 68 | 5. Build projects around motivated individuals. Give them the environment and support they need and trust them to get the job done. ++ 69 | 6. The most efficient and effective method of conveying information to and within a development team is face to face conversation. 70 | 7. Working software is the primary measure of progress. ++ 71 | 8. Agile processes promote sustainable development. The sponsors, developers, and users should be able to maintain a constant pace indefinitely. 72 | 9. Continuous attention to technical excellence and good design enhances agility. 73 | 10. Simplicity -- the art of maximizing the amount of work done -- is essential. 74 | 11. The best architecture , requirements and designs emerge from self organizing teams. ++ 75 | 12. At regular interval, the team reflects on how to become more effective, then tunes and adjusts its behavior accordingly. 76 | 77 | -------------------------------------------------------------------- 78 | Manifesto for Software Craftsmanship 79 | As aspiring software craftsman we are raising the bar of professional software development by practicing it and helping others learn the craft. Through this work we have come to value: 80 | Not only working software, but also well crafted software 81 | Not only responding to change, but also steadily adding value 82 | Not only individuals and interactions, but also a community of professionals 83 | Not only customer collaboration, but also productive partnerships 84 | That is in pursuit of items on the left, we have found the items on the right to be indispensable. 85 | 1. Well crafted software 86 | 2. Steadily adding value 87 | 3. Community of professionals 88 | 4. Productive partnerships 89 | 90 | -------------------------------------------------------------------- 91 | 92 | working software is the goal. as fast and good as possible. write simple, efficient, maintainable code. iterative software development. 100% quality is an iterative process, continuous refactoring of the code base ... 93 | innovation is 1% inspiration and 99% perspiration(syntactic sugar sweet sweat), innovators, risk lovers, take calculated risks, large knowledge base -> connect many algorithms, formalize new ones, the base is a large knowledge base ... trial and error process 94 | 95 | if god were among us, we would hold him for completely irrational, because he would never do the same thing twice ... 96 | 97 | push it to the limit. it's all about progress, make our projects progress, make our knowledge base progress, make technology progress, help make the world a better place for all, for the future generations, for they shall have all the comfort of automation and then build on it. imagine the world in 100 years time. what will it be like? if we are able to figure that out now, jackpot ... 100 years ahead ... progress of the human mind .. evolution ... revolution ... many disruptive technologies ahead ... make new ... let's have a lot of fun in the process ... just for fun ... 98 | let's build the future with love ... the future starts now ... in a perfect world ... what would a perfect world be like ? 99 | 100 | what is the sex of the angels? we pondered on this topic in university. i'd say stateless. they must be good and pure, like a new born baby. intellectual masturbation time. some people get paid to do this and professors love talking. talk is cheap, show me the algorithms, facts and nothing but facts. numbers and more numbers and i will believe. 101 | results count. working software. get it done as good and fast as possible that is our reality. the meaning of life is progress. 102 | with great powers come great responsibilities ... all humans are equal ... i have a dream ... and will push it through to completion ... 103 | i hope everybody has a dream and is living their dreams ... everything starts with a dream ... live your dream ... stream it ... 104 | -------------------------------------------------------------------------------- /cppplaydesignpatterns.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2013 4 | VisualStudioVersion = 12.0.31101.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "cppplaydesignpatterns", "cppplaydesignpatterns\cppplaydesignpatterns.vcxproj", "{608DE9D9-A760-4BC4-8F23-7983215C6411}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Win32 = Debug|Win32 11 | Release|Win32 = Release|Win32 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {608DE9D9-A760-4BC4-8F23-7983215C6411}.Debug|Win32.ActiveCfg = Debug|Win32 15 | {608DE9D9-A760-4BC4-8F23-7983215C6411}.Debug|Win32.Build.0 = Debug|Win32 16 | {608DE9D9-A760-4BC4-8F23-7983215C6411}.Release|Win32.ActiveCfg = Release|Win32 17 | {608DE9D9-A760-4BC4-8F23-7983215C6411}.Release|Win32.Build.0 = Release|Win32 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | EndGlobal 23 | -------------------------------------------------------------------------------- /cppplaydesignpatterns.v12.suo: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns.v12.suo -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/abstractfactory.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/abstractfactory.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/adapter.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/adapter.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/adapter1.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/adapter1.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/bridge.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/bridge.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/builder.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/builder.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/chainofresponsibility.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/chainofresponsibility.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/command1.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/command1.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/composite.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/composite.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/composite1.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/composite1.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/cor_broker.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/cor_broker.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/cor_pointer.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/cor_pointer.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/cppplayd.608DE9D9.tlog/CL.read.1.tlog: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/cppplayd.608DE9D9.tlog/CL.read.1.tlog -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/cppplayd.608DE9D9.tlog/CL.write.1.tlog: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/cppplayd.608DE9D9.tlog/CL.write.1.tlog -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/cppplayd.608DE9D9.tlog/cl.command.1.tlog: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/cppplayd.608DE9D9.tlog/cl.command.1.tlog -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/cppplayd.608DE9D9.tlog/cppplaydesignpatterns.lastbuildstate: -------------------------------------------------------------------------------- 1 | #TargetFrameworkVersion=v4.0:PlatformToolSet=v120:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit 2 | Debug|Win32|C:\Users\Nils\Documents\Visual Studio 2013\Projects\cppplaydesignpatterns\| 3 | -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/cppplayd.608DE9D9.tlog/link.command.1.tlog: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/cppplayd.608DE9D9.tlog/link.command.1.tlog -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/cppplayd.608DE9D9.tlog/link.read.1.tlog: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/cppplayd.608DE9D9.tlog/link.read.1.tlog -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/cppplayd.608DE9D9.tlog/link.write.1.tlog: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/cppplayd.608DE9D9.tlog/link.write.1.tlog -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/cppplaydesignpatterns.Build.CppClean.log: -------------------------------------------------------------------------------- 1 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\vc120.pdb 2 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\vc120.idb 3 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\cor_pointer.obj 4 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\composite.obj 5 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\composite1.obj 6 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\decorator.obj 7 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\decorator1.obj 8 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\facade.obj 9 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\flyweight.obj 10 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\interpreter.obj 11 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\iterator.obj 12 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\mediator.obj 13 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\memento.obj 14 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\prototype.obj 15 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\observer.obj 16 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\observerboost.obj 17 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\singleton.obj 18 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\virtualproxy.obj 19 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\state1.obj 20 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\state2.obj 21 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\strategy_dynamic.obj 22 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\template.obj 23 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\abstractfactory.obj 24 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\adapter.obj 25 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\adapter1.obj 26 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\bridge.obj 27 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\builder.obj 28 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\chainofresponsibility.obj 29 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\command1.obj 30 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\factorymethod.obj 31 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\cor_broker.obj 32 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\debug\cppplaydesignpatterns.ilk 33 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\debug\cppplaydesignpatterns.exe 34 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\debug\cppplaydesignpatterns.pdb 35 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\cppplayd.608de9d9.tlog\cl.command.1.tlog 36 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\cppplayd.608de9d9.tlog\cl.read.1.tlog 37 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\cppplayd.608de9d9.tlog\cl.write.1.tlog 38 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\cppplayd.608de9d9.tlog\link.command.1.tlog 39 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\cppplayd.608de9d9.tlog\link.read.1.tlog 40 | c:\users\nils\documents\visual studio 2013\projects\cppplaydesignpatterns\cppplaydesignpatterns\debug\cppplayd.608de9d9.tlog\link.write.1.tlog 41 | -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/cppplaydesignpatterns.log: -------------------------------------------------------------------------------- 1 | Build started 05.11.2016 11:01:36. 2 | 1>Project "C:\Users\Nils\Documents\Visual Studio 2013\Projects\cppplaydesignpatterns\cppplaydesignpatterns\cppplaydesignpatterns.vcxproj" on node 2 (Build target(s)). 3 | 1>ClCompile: 4 | C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\CL.exe /c /ZI /nologo /W3 /WX- /Od /Oy- /D WIN32 /D _SCL_SECURE_NO_WARNINGS /Gm /EHsc /RTC1 /MDd /GS /fp:precise /Zc:wchar_t /Zc:forScope /Fo"Debug\\" /Fd"Debug\vc120.pdb" /Gd /TP /analyze- /errorReport:prompt visitor.cpp 5 | visitor.cpp 6 | Unknown compiler version - please run the configure tests and report the results 7 | Link: 8 | C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\link.exe /ERRORREPORT:PROMPT /OUT:"C:\Users\Nils\Documents\Visual Studio 2013\Projects\cppplaydesignpatterns\Debug\cppplaydesignpatterns.exe" /INCREMENTAL /NOLOGO kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /MANIFEST /MANIFESTUAC:"level='asInvoker' uiAccess='false'" /manifest:embed /DEBUG /PDB:"C:\Users\Nils\Documents\Visual Studio 2013\Projects\cppplaydesignpatterns\Debug\cppplaydesignpatterns.pdb" /SUBSYSTEM:CONSOLE /TLBID:1 /DYNAMICBASE /NXCOMPAT /IMPLIB:"C:\Users\Nils\Documents\Visual Studio 2013\Projects\cppplaydesignpatterns\Debug\cppplaydesignpatterns.lib" /MACHINE:X86 Debug\abstractfactory.obj 9 | Debug\adapter.obj 10 | Debug\adapter1.obj 11 | Debug\bridge.obj 12 | Debug\builder.obj 13 | Debug\chainofresponsibility.obj 14 | Debug\command1.obj 15 | Debug\factorymethod.obj 16 | Debug\cor_broker.obj 17 | Debug\cor_pointer.obj 18 | Debug\composite.obj 19 | Debug\composite1.obj 20 | Debug\decorator.obj 21 | Debug\decorator1.obj 22 | Debug\facade.obj 23 | Debug\flyweight.obj 24 | Debug\interpreter.obj 25 | Debug\iterator.obj 26 | Debug\mediator.obj 27 | Debug\memento.obj 28 | Debug\prototype.obj 29 | Debug\observer.obj 30 | Debug\observerboost.obj 31 | Debug\singleton.obj 32 | Debug\virtualproxy.obj 33 | Debug\state1.obj 34 | Debug\state2.obj 35 | Debug\strategy_dynamic.obj 36 | Debug\template.obj 37 | Debug\visitor.obj 38 | cppplaydesignpatterns.vcxproj -> C:\Users\Nils\Documents\Visual Studio 2013\Projects\cppplaydesignpatterns\Debug\cppplaydesignpatterns.exe 39 | 1>Done Building Project "C:\Users\Nils\Documents\Visual Studio 2013\Projects\cppplaydesignpatterns\cppplaydesignpatterns\cppplaydesignpatterns.vcxproj" (Build target(s)). 40 | 41 | Build succeeded. 42 | 43 | Time Elapsed 00:00:09.75 44 | -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/decorator.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/decorator.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/decorator1.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/decorator1.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/facade.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/facade.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/factorymethod.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/factorymethod.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/flyweight.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/flyweight.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/interpreter.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/interpreter.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/iterator.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/iterator.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/mediator.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/mediator.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/memento.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/memento.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/observer.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/observer.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/observerboost.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/observerboost.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/prototype.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/prototype.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/singleton.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/singleton.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/state1.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/state1.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/state2.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/state2.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/strategy_dynamic.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/strategy_dynamic.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/template.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/template.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/vc120.idb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/vc120.idb -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/vc120.pdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/vc120.pdb -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/virtualproxy.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/virtualproxy.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/Debug/visitor.obj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NilsHolger/cppplaydesignpatterns/81f539646a479b82e4a64fd78ddbdff3a5827072/cppplaydesignpatterns/Debug/visitor.obj -------------------------------------------------------------------------------- /cppplaydesignpatterns/abstractfactory.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h" 2 | #include "hottechnology.h" 3 | 4 | using namespace std; 5 | unique_ptr make_t(string t) 6 | { 7 | unique_ptr ht; 8 | if (t == "a") 9 | { 10 | ht = make_unique(); 11 | ht->b(100); 12 | } 13 | else 14 | { 15 | ht = make_unique(); 16 | ht->b(10); 17 | } 18 | return ht; 19 | } 20 | //auto main() -> int 21 | //{ 22 | // auto a = make_t("a"); 23 | // getchar(); 24 | //} -------------------------------------------------------------------------------- /cppplaydesignpatterns/adapter.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h" 2 | using namespace std; 3 | 4 | class String { 5 | string s; 6 | public: 7 | String(const string &s) : s(s){} 8 | String to_lower_copy()const { 9 | return boost::to_lower_copy(s); 10 | } 11 | vector split(const string& delimeter = " ")const { 12 | vector parts; 13 | boost::split(parts, s, boost::is_any_of(delimeter), boost::token_compress_on); 14 | return vector(parts.begin(), parts.end()); 15 | } 16 | size_t get_length() const { return s.length(); }; 17 | }; 18 | 19 | //int main(){ 20 | // 21 | // String s{ "You Sexy String" }; 22 | // for (auto& t : s.to_lower_copy().split()){ cout << t.get_length() << '\n'; }; 23 | // 24 | //} -------------------------------------------------------------------------------- /cppplaydesignpatterns/adapter1.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h" 2 | using namespace std; 3 | typedef int Coordinate; 4 | typedef int Dimension; 5 | 6 | //desired interface 7 | class Rectangle { 8 | public: 9 | virtual void draw() = 0; 10 | }; 11 | 12 | //legacy component 13 | class LegacyRectangle { 14 | public: 15 | LegacyRectangle(Coordinate x1, Coordinate y1, Coordinate x2, Coordinate y2){ 16 | x1_ = x1; 17 | y1_ = y1; 18 | x2_ = x2; 19 | y2_ = y2; 20 | cout << "LegacyRectangle: create. (" << x1_ << "," << y1_ << ") => (" 21 | << x2_ << "," << y2_ << ")" << "\n"; 22 | } 23 | void oldDraw(){ 24 | cout << "LegacyRectangle: oldDraw. (" << x1_ << "," << y1_ << 25 | ") => (" << x2_ << "," << y2_ << ")" << '\n'; 26 | } 27 | private: 28 | Coordinate x1_; 29 | Coordinate y1_; 30 | Coordinate x2_; 31 | Coordinate y2_; 32 | }; 33 | class RectangleAdapter : public Rectangle, private LegacyRectangle { 34 | public: 35 | RectangleAdapter(Coordinate x, Coordinate y, Dimension w, Dimension h) 36 | : LegacyRectangle(x, y, x + w, y + h) 37 | { 38 | cout << "RectangleAdapter: create. (" << x << "," << y << "), width =" 39 | << w << ", height = " << h << '\n'; 40 | } 41 | virtual void draw() 42 | { 43 | cout << "RectangleAdapter: draw " << '\n'; 44 | oldDraw(); 45 | } 46 | }; 47 | 48 | //int main() { 49 | // Rectangle *r = new RectangleAdapter(40, 100, 20, 10); 50 | // r->draw(); 51 | //} -------------------------------------------------------------------------------- /cppplaydesignpatterns/bridge.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h"; 2 | using namespace std; 3 | 4 | class TimeImp { 5 | public: 6 | TimeImp(int hr, int min) { 7 | hr_ = hr; 8 | min_ = min; 9 | } 10 | virtual void tellmeallyoursecrets() { 11 | cout << "time is " << hr_ << ':' << min_ << endl; 12 | } 13 | protected: 14 | int hr_, min_; 15 | }; 16 | 17 | class CivilianTimeImp : public TimeImp { 18 | public: 19 | CivilianTimeImp(int hr, int min, int pm) : TimeImp(hr, min) { 20 | pm ? strcpy(whichM_, " PM") : strcpy(whichM_, " AM"); 21 | } 22 | 23 | void tellmeallyoursecrets() { 24 | cout << "time is " << hr_ << ':' << min_ << whichM_ << endl; 25 | } 26 | protected: 27 | char whichM_[4]; 28 | }; 29 | 30 | class ZuluTimeImp : public TimeImp { 31 | public: 32 | ZuluTimeImp(int hr, int min, int zone) : TimeImp(hr, min) { 33 | zone ? strcpy(zone_, " D Standard Time") : strcpy(zone_, " ROW Standard Time"); 34 | } 35 | void tellmeallyoursecrets() { 36 | cout << "time is " << hr_ << ':' << min_ << zone_ << 37 | endl; 38 | } 39 | protected: 40 | char zone_[30]; 41 | }; 42 | 43 | class Time { 44 | public: 45 | Time(){} 46 | Time(int hr, int min) { 47 | imp_ = new TimeImp(hr, min); 48 | } 49 | virtual void tellmeallyoursecrets() { 50 | imp_->tellmeallyoursecrets(); 51 | } 52 | protected: 53 | TimeImp *imp_; 54 | }; 55 | 56 | class CivilianTime : public Time { 57 | public: 58 | CivilianTime(int hr, int min, int pm) { 59 | imp_ = new CivilianTimeImp(hr, min, pm); 60 | } 61 | }; 62 | 63 | class ZuluTime : public Time { 64 | public: 65 | ZuluTime(int hr, int min, int zone) { 66 | imp_ = new ZuluTimeImp(hr, min, zone); 67 | } 68 | }; 69 | 70 | //auto main() -> int 71 | //{ 72 | // Time *times[3]; 73 | // times[0] = new Time(11, 11); 74 | // times[1] = new CivilianTime(11, 11, 1); 75 | // times[2] = new ZuluTime(11, 11, 1); 76 | // for (int i = 2; i >= 0; --i){ 77 | // times[i]->tellmeallyoursecrets(); 78 | // } 79 | // getchar(); 80 | //} -------------------------------------------------------------------------------- /cppplaydesignpatterns/builder.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h" 2 | using namespace std; 3 | 4 | struct HtmlBuilder; 5 | 6 | struct HtmlElement { 7 | string name; 8 | string text; 9 | vector elements; 10 | const size_t indent_size = 2; 11 | HtmlElement(){} 12 | HtmlElement(const string &name, const string &text) : name(name), text(text) {} 13 | string str(int indent = 0) const { 14 | ostringstream oss; 15 | string i(indent_size * indent, ' '); 16 | oss << i << "<" << name << ">" << '\n'; 17 | if (text.size() > 0){ 18 | oss << string(indent_size*(indent + 1), ' ') << text << '\n'; 19 | } 20 | for (const auto & e : elements){ 21 | oss << e.str(indent + 1); 22 | } 23 | 24 | oss << i << "" << '\n'; 25 | return oss.str(); 26 | } 27 | 28 | static unique_ptr build(string root_name){ 29 | return make_unique(root_name); 30 | } 31 | }; 32 | struct HtmlBuilder 33 | { 34 | HtmlBuilder(string root_name) 35 | { 36 | root.name = root_name; 37 | } 38 | 39 | HtmlBuilder& add_child(string child_name, string child_text){ 40 | HtmlElement e{ child_name, child_text }; 41 | root.elements.emplace_back(e); 42 | return *this; 43 | } 44 | 45 | string str() { return root.str(); } 46 | 47 | operator HtmlElement() const { return root; } 48 | HtmlElement root; 49 | }; 50 | 51 | 52 | //int main() { 53 | // HtmlBuilder builder{ "ul" }; 54 | // builder.add_child("li", "get").add_child("li", "stuff").add_child("li", "done"); 55 | // cout << builder.str() << '\n'; 56 | // HtmlElement e = HtmlElement::build("ul")->add_child("li", "you").add_child("li", "sexy") 57 | // .add_child("li", "string"); 58 | // cout << e.str() << '\n'; 59 | //} -------------------------------------------------------------------------------- /cppplaydesignpatterns/chainofresponsibility.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h" 2 | using namespace std; 3 | class Base { 4 | //next pointer in base class 5 | Base *next; 6 | public: 7 | Base() 8 | { 9 | next = 0; 10 | } 11 | void setNext(Base *n) 12 | { 13 | next = n; 14 | } 15 | void add(Base *n) 16 | { 17 | if (next){ next->add(n); } 18 | else { next = n; } 19 | } 20 | //chain method always delegates to next obj 21 | virtual void handle(int i) 22 | { 23 | next->handle(i); 24 | } 25 | }; 26 | class Handler1 : public Base 27 | { 28 | public: 29 | void handle(int i) 30 | { 31 | if (rand() % 4) 32 | { 33 | cout << "H1 passed " << i << " "; 34 | Base::handle(i); 35 | } 36 | else 37 | { 38 | cout << "H1 handled " << i << " "; 39 | } 40 | } 41 | }; 42 | 43 | class Handler2 : public Base 44 | { 45 | public: 46 | void handle(int i) 47 | { 48 | if (rand() % 4) 49 | { 50 | cout << "H2 passed " << i << " "; 51 | Base::handle(i); 52 | } 53 | else 54 | { 55 | cout << "H2 handled " << i << " "; 56 | } 57 | } 58 | }; 59 | 60 | class Handler3 : public Base 61 | { 62 | public: 63 | void handle(int i) 64 | { 65 | if (rand() % 4) 66 | { 67 | cout << "H3 passed " << i << " "; 68 | Base::handle(i); 69 | } 70 | else 71 | { 72 | cout << "H3 handled " << i << " "; 73 | } 74 | } 75 | }; 76 | class Handler4 : public Base 77 | { 78 | public: 79 | void handle(int i) 80 | { 81 | if (rand() % 4) 82 | { 83 | cout << "H4 passed " << i << " "; 84 | Base::handle(i); 85 | } 86 | else 87 | { 88 | cout << "H4 handled " << i << " "; 89 | } 90 | } 91 | }; 92 | 93 | //auto main() -> int 94 | //{ 95 | // srand(time(0)); 96 | // Handler1 root;Handler2 two;Handler3 three;Handler4 four; 97 | // root.add(&two);root.add(&three);root.add(&four);four.setNext(&root); 98 | // for (int i = 1; i < 10; i++) 99 | // { 100 | // root.handle(i); 101 | // cout << '\n'; 102 | // } 103 | //} -------------------------------------------------------------------------------- /cppplaydesignpatterns/command1.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h" 2 | using namespace std; 3 | class Person; 4 | 5 | class Command 6 | { 7 | Person *object; 8 | void(Person:: *method)(); 9 | public: 10 | Command(Person *obj = 0, void(Person:: *meth)() = 0) 11 | { 12 | object = obj; 13 | method = meth; 14 | } 15 | void execute() 16 | { 17 | (object->*method)(); 18 | } 19 | }; 20 | 21 | class Person 22 | { 23 | string name; 24 | Command cmd; 25 | public: 26 | Person(string n, Command c) : cmd(c) 27 | { 28 | name = n; 29 | } 30 | void talk() 31 | { 32 | cout << name << " is talking" << '\n'; 33 | cmd.execute(); 34 | } 35 | void passOn() 36 | { 37 | cout << name << " is passing on" << '\n'; 38 | cmd.execute(); 39 | } 40 | void gossip() 41 | { 42 | cout << name << " is gossiping" << '\n'; 43 | cmd.execute(); 44 | } 45 | void listen() 46 | { 47 | cout << name << " is listening" << '\n'; 48 | } 49 | }; 50 | 51 | //auto main() -> int 52 | //{ 53 | // Person carol("Carol", Command()); 54 | // Person mary("Mary", Command(&carol, &Person::listen)); 55 | // Person bettina("Bettina", Command(&mary, &Person::gossip)); 56 | // Person sophie("Sophie", Command(&bettina, &Person::passOn)); 57 | // sophie.talk(); 58 | //} 59 | -------------------------------------------------------------------------------- /cppplaydesignpatterns/composite.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h" 2 | using namespace std; 3 | //interface lowest common denominator 4 | class Component { 5 | public: 6 | virtual void traverse() = 0; 7 | }; 8 | 9 | class Leaf : public Component 10 | { 11 | //scalar class/ is a relationship 12 | int value; 13 | public: 14 | Leaf(int val){ 15 | value = val; 16 | } 17 | void traverse(){ 18 | cout << value << ' '; 19 | } 20 | }; 21 | class Composite : public Component 22 | { 23 | //vector class/is a relationship 24 | vector children; 25 | public: 26 | //container class coupled to interface 27 | void add(Component *ele){ 28 | children.push_back(ele); 29 | } 30 | void traverse(){ 31 | for (int i = 0; i < children.size(); i++){ 32 | //polymorphism delegate to children 33 | children[i]->traverse(); 34 | } 35 | } 36 | }; 37 | //int main(){ 38 | // const int cmb = 4; 39 | // const int lmb = 3; 40 | // Composite containers[cmb]; 41 | // for (int i = 0; i < cmb; i++){ 42 | // for (int j = 0; j < lmb; j++) { 43 | // containers[i].add(new Leaf(i * lmb + j)); 44 | // } 45 | // } 46 | // for (int i = 1; i < cmb; i++){ 47 | // containers[0].add(&(containers[i])); 48 | // } 49 | // for (int i = 0; i < cmb; i++){ 50 | // containers[i].traverse(); 51 | // cout << '\n'; 52 | // } 53 | //} -------------------------------------------------------------------------------- /cppplaydesignpatterns/composite1.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h" 2 | using namespace std; 3 | 4 | 5 | -------------------------------------------------------------------------------- /cppplaydesignpatterns/cor_broker.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h" 2 | using namespace std; 3 | //using namespace boost::signals2; 4 | 5 | struct Query 6 | { 7 | string animal_name; 8 | enum Argument { attack, defense}argument; 9 | int result; 10 | Query(const string& animal_name, const Argument argument, const int result) : 11 | animal_name(animal_name), argument(argument), result(result){} 12 | }; 13 | struct Game 14 | { 15 | boost::signals2::signal queries; 16 | }; 17 | 18 | struct Animal 19 | { 20 | Game& game; 21 | int attack, defense; 22 | public: 23 | Animal(Game& game, const int attack, const int defense, const string& name) : 24 | game(game), attack(attack), defense(defense), name(name){} 25 | string name; 26 | int GetAttack() const 27 | { 28 | Query q{ name, Query::Argument::attack, attack }; 29 | game.queries(q); 30 | return q.result; 31 | } 32 | int GetDefense() const 33 | { 34 | Query q{ name, Query::Argument::defense, defense }; 35 | game.queries(q); 36 | return q.result; 37 | } 38 | friend std::ostream& operator << (std::ostream& os, const Animal& obj) 39 | { 40 | return os 41 | << "attack: " << obj.GetAttack() 42 | << " defense: " << obj.GetDefense() 43 | << " name: " << obj.name; 44 | } 45 | }; 46 | class AnimalModifier 47 | { 48 | Game& game; 49 | Animal& animal; 50 | public: 51 | AnimalModifier(Game& game, Animal& animal) : game(game), animal(animal){} 52 | virtual ~AnimalModifier() = default; 53 | }; 54 | 55 | class DoubleAttackModifier : public AnimalModifier 56 | { 57 | boost::signals2::connection conn; 58 | public: 59 | DoubleAttackModifier(Game& game, Animal& animal) : AnimalModifier(game, animal) 60 | { 61 | game.queries.connect([&](Query& q) 62 | { 63 | if (q.animal_name == animal.name && 64 | q.argument == Query::Argument::attack) 65 | { 66 | q.result *= 10; 67 | } 68 | else if (q.animal_name == animal.name && 69 | q.argument == Query::Argument::defense) 70 | { 71 | q.result *= 100; 72 | } 73 | }); 74 | } 75 | virtual ~DoubleAttackModifier() 76 | { 77 | conn.disconnect(); 78 | } 79 | }; 80 | 81 | //auto main() -> int 82 | //{ 83 | // Game game; 84 | // Animal lion{ game, 10, 10, "Open Source" }; 85 | // cout << lion << '\n'; 86 | // DoubleAttackModifier d{ game, lion }; 87 | // cout << lion << '\n'; 88 | //} -------------------------------------------------------------------------------- /cppplaydesignpatterns/cor_pointer.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h" 2 | using namespace std; 3 | struct Animal 4 | { 5 | string name; 6 | int attack, defense; 7 | Animal(const string& name, const int attack, const int defense) 8 | : name(name), 9 | attack(attack), 10 | defense(defense) 11 | { 12 | } 13 | friend std::ostream& operator<<(std::ostream& os, const Animal& obj) 14 | { 15 | return os 16 | << "name: " << obj.name 17 | << " attack: " << obj.attack 18 | << " defense: " << obj.defense; 19 | } 20 | }; 21 | class AnimalModifier 22 | { 23 | AnimalModifier* next = nullptr; 24 | protected: 25 | Animal& animal; 26 | public: 27 | 28 | explicit AnimalModifier(Animal& animal) 29 | : animal(animal) 30 | { 31 | } 32 | virtual ~AnimalModifier() = default; 33 | 34 | void add(AnimalModifier* cm) 35 | { 36 | if (next) next->add(cm); 37 | else next = cm; 38 | } 39 | virtual void handle() 40 | { 41 | if (next) next->handle(); 42 | } 43 | }; 44 | class NoBonusModifier : public AnimalModifier 45 | { 46 | public: 47 | explicit NoBonusModifier(Animal& animal) 48 | : AnimalModifier(animal) 49 | { 50 | } 51 | void handle() override 52 | { 53 | } 54 | }; 55 | 56 | class DoubleAttackModifier : public AnimalModifier 57 | { 58 | public: 59 | explicit DoubleAttackModifier(Animal& creature) 60 | : AnimalModifier(creature) 61 | { 62 | } 63 | void handle() override 64 | { 65 | animal.attack *= 2; 66 | AnimalModifier::handle(); 67 | } 68 | }; 69 | class IncreaseDefenseModifier : public AnimalModifier 70 | { 71 | public: 72 | explicit IncreaseDefenseModifier(Animal& creature) 73 | : AnimalModifier(creature) 74 | { 75 | } 76 | void handle() override 77 | { 78 | if (animal.attack <= 2) 79 | animal.defense++; 80 | AnimalModifier::handle(); 81 | } 82 | }; 83 | 84 | //auto main() -> int 85 | //{ 86 | // Animal lion{ "Lion", 1, 1 }; 87 | // AnimalModifier root{ lion }; 88 | // DoubleAttackModifier r1{ lion }; 89 | // DoubleAttackModifier r1_2{ lion }; 90 | // IncreaseDefenseModifier r2{ lion }; 91 | // //NoBonusModifier nob{ lion }; 92 | // //root.add(&nob); 93 | // root.add(&r1); 94 | // root.add(&r1_2); 95 | // root.add(&r2); 96 | // root.handle(); 97 | // cout << lion << '\n'; 98 | //} 99 | -------------------------------------------------------------------------------- /cppplaydesignpatterns/cppplaydesignpatterns.vcxproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | 14 | {608DE9D9-A760-4BC4-8F23-7983215C6411} 15 | Win32Proj 16 | cppplaydesignpatterns 17 | 18 | 19 | 20 | Application 21 | true 22 | v120 23 | Unicode 24 | 25 | 26 | Application 27 | false 28 | v120 29 | true 30 | Unicode 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 81a925c4 43 | 44 | 45 | true 46 | $(VC_IncludePath);$(WindowsSDK_IncludePath);C:\Users\Nils\Downloads\boost_1_51_0; 47 | 48 | 49 | false 50 | $(VC_IncludePath);$(WindowsSDK_IncludePath);C:\Users\Nils\Downloads\boost_1_51_0; 51 | 52 | 53 | 54 | 55 | 56 | Level3 57 | Disabled 58 | WIN32;_SCL_SECURE_NO_WARNINGS 59 | %(AdditionalIncludeDirectories) 60 | 61 | 62 | Console 63 | true 64 | %(AdditionalLibraryDirectories) 65 | %(AdditionalDependencies) 66 | 67 | 68 | 69 | 70 | Level3 71 | 72 | 73 | MaxSpeed 74 | true 75 | true 76 | WIN32;_SCL_SECURE_NO_WARNINGS 77 | %(AdditionalIncludeDirectories) 78 | 79 | 80 | Console 81 | true 82 | true 83 | true 84 | %(AdditionalLibraryDirectories) 85 | %(AdditionalDependencies) 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 131 | 132 | 133 | 134 | -------------------------------------------------------------------------------- /cppplaydesignpatterns/cppplaydesignpatterns.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hh;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Header Files 20 | 21 | 22 | Header Files 23 | 24 | 25 | 26 | 27 | Source Files 28 | 29 | 30 | Source Files 31 | 32 | 33 | Source Files 34 | 35 | 36 | Source Files 37 | 38 | 39 | Source Files 40 | 41 | 42 | Source Files 43 | 44 | 45 | Source Files 46 | 47 | 48 | Source Files 49 | 50 | 51 | Source Files 52 | 53 | 54 | Source Files 55 | 56 | 57 | Source Files 58 | 59 | 60 | Source Files 61 | 62 | 63 | Source Files 64 | 65 | 66 | Source Files 67 | 68 | 69 | Source Files 70 | 71 | 72 | Source Files 73 | 74 | 75 | Source Files 76 | 77 | 78 | Source Files 79 | 80 | 81 | Source Files 82 | 83 | 84 | Source Files 85 | 86 | 87 | Source Files 88 | 89 | 90 | Source Files 91 | 92 | 93 | Source Files 94 | 95 | 96 | Source Files 97 | 98 | 99 | Source Files 100 | 101 | 102 | Source Files 103 | 104 | 105 | Source Files 106 | 107 | 108 | Source Files 109 | 110 | 111 | Source Files 112 | 113 | 114 | Source Files 115 | 116 | 117 | -------------------------------------------------------------------------------- /cppplaydesignpatterns/cppplaydesignpatterns.vcxproj.user: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | true 5 | 6 | -------------------------------------------------------------------------------- /cppplaydesignpatterns/decorator.cpp: -------------------------------------------------------------------------------- 1 | //#include "headers.h" 2 | //using namespace std; 3 | // 4 | //struct Shape { 5 | // virtual string str() const = 0; 6 | //}; 7 | //struct Circle : Shape { 8 | // float radius; 9 | // explicit Circle(const float radius): radius{radius}{} 10 | // string str() const override 11 | // { 12 | // ostringstream oss; 13 | // oss << "circle with radius " << radius; 14 | // return oss.str(); 15 | // } 16 | //}; 17 | //struct Square : Shape { 18 | // float side; 19 | // explicit Square(const float side) : side(side){} 20 | // string str() const override 21 | // { 22 | // ostringstream oss; 23 | // oss << "square with side " << side; 24 | // } 25 | //}; 26 | //struct ColoredShape : Shape 27 | //{ 28 | // Shape& shape; 29 | // string color; 30 | // ColoredShape(Shape& shape, const string& color): shape{shape}, color{color}{} 31 | // string str() const override 32 | // { 33 | // ostringstream oss; 34 | // oss << shape.str() << " has color " << color; 35 | // return oss.str(); 36 | // } 37 | //}; 38 | //struct TransparentShape : Shape 39 | //{ 40 | // Shape& shape; 41 | // uint8_t transparency; 42 | // TransparentShape(Shape& shape, const uint8_t transparency): shape{shape}, transparency{transparency}{} 43 | // string str() const override 44 | // { 45 | // ostringstream oss; 46 | // oss << shape.str() << " has " << static_cast(transparency) / 255.f * 100.f << " % transparency"; 47 | // return oss.str(); 48 | // } 49 | //}; 50 | // 51 | //int main(){ 52 | // Circle c{10}; 53 | // cout << c.str() << '\n'; 54 | // ColoredShape blue_c{c, "blue"}; 55 | // cout << blue_c.str() << '\n'; 56 | // TransparentShape qrtr_trpnt_c{c, 64}; 57 | // cout << qrtr_trpnt_c.str() << '\n'; 58 | // TransparentShape ten_trpnt_blue_c{blue_c, 25}; 59 | // cout << ten_trpnt_blue_c.str() << '\n'; 60 | //} 61 | -------------------------------------------------------------------------------- /cppplaydesignpatterns/decorator1.cpp: -------------------------------------------------------------------------------- 1 | //#include "headers.h" 2 | //using namespace std; 3 | // 4 | //struct Logger { 5 | // function func; 6 | // string name; 7 | // Logger(const function& func, const string& name) : 8 | // func{ func }, name{ name }{} 9 | // void operator()() const { 10 | // cout << "entering " << name << '\n'; 11 | // func(); 12 | // cout << "exiting " << name << '\n'; 13 | // } 14 | //}; 15 | //template 16 | //struct Logger1 { 17 | // Func func; 18 | // string name; 19 | // Logger1(Func func, const string& name) : 20 | // func{ func }, name{ name }{} 21 | // void operator()() const { 22 | // cout << "entering " << name << '\n'; 23 | // func(); 24 | // cout << "exiting " << name << '\n'; 25 | // } 26 | //}; 27 | //template auto make_logger1(Func func, const string& name){ 28 | // return Logger1{func, name}; 29 | //} 30 | //template 31 | //struct Logger2{ 32 | // function func; 33 | // string name; 34 | // Logger2(const function ) 35 | //}; 36 | 37 | 38 | //int main(){ 39 | // auto logger = make_logger1([](){ cout << "Hello" << '\n'; }, "HelloFunc"); 40 | // logger(); 41 | //} -------------------------------------------------------------------------------- /cppplaydesignpatterns/facade.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h" 2 | 3 | using namespace std; 4 | 5 | class MissDepartment 6 | { 7 | public: 8 | void submitNetworkRequest() 9 | { 10 | _state = 0; 11 | } 12 | bool checkOnStatus() 13 | { 14 | _state++; 15 | return (_state == Complete) ? 1 : 0; 16 | } 17 | private: 18 | enum States 19 | { 20 | Received, DenyAllKnowledge, ReferClientToFacilities, 21 | FacilitiesHasNotSentPaperwork, ElectricianIsNotDone, 22 | ElectricianDidItWrong, DispatchTechnician, SignedOff, DoesNotWork, 23 | FixElectriciansWiring, Complete 24 | }; 25 | int _state; 26 | }; 27 | 28 | class ElectricianUnion 29 | { 30 | public: 31 | void submitNetworkRequest() 32 | { 33 | _state = 0; 34 | } 35 | bool checkOnStatus() 36 | { 37 | _state++; 38 | return (_state == Complete) ? 1 : 0; 39 | } 40 | private: 41 | enum States 42 | { 43 | Received, RejectTheForm, SizeTheJob, SmokeAndJokeBreak, 44 | WaitForAuthorization, DoTheWrongJob, BlameTheEngineer, WaitToPunchOut, 45 | DoHalfAJob, ComplainToEngineer, GetClarification, CompleteTheJob, 46 | TurnInThePaperwork, Complete 47 | }; 48 | int _state; 49 | }; 50 | 51 | class FacilitiesDepartment 52 | { 53 | public: 54 | void submitNetworkRequest() 55 | { 56 | _state = 0; 57 | } 58 | bool checkOnStatus() 59 | { 60 | _state++; 61 | return (_state == Complete) ? 1 : 0; 62 | } 63 | private: 64 | enum States 65 | { 66 | Received, AssignToEngineer, EngineerResearches, RequestIsNotPossible, 67 | EngineerLeavesCompany, AssignToNewEngineer, NewEngineerResearches, 68 | ReassignEngineer, EngineerReturns, EngineerResearchesAgain, 69 | EngineerFillsOutPaperWork, Complete 70 | }; 71 | int _state; 72 | }; 73 | 74 | class FacilitiesFacade 75 | { 76 | public: 77 | FacilitiesFacade() 78 | { 79 | _count = 0; 80 | } 81 | void submitNetworkRequest() 82 | { 83 | _state = 0; 84 | } 85 | bool checkOnStatus() 86 | { 87 | _count++; 88 | if (_state == Received) 89 | { 90 | _state++; 91 | _engineer.submitNetworkRequest(); 92 | cout << "submitted to Facilities - " << _count << 93 | " phone calls so far" << '\n'; 94 | } 95 | else if (_state == SubmitToEngineer) 96 | { 97 | if (_engineer.checkOnStatus()) 98 | { 99 | _state++; 100 | _electrician.submitNetworkRequest(); 101 | cout << "submitted to Electrician - " << _count << 102 | " phone calls so far" << '\n'; 103 | } 104 | } 105 | else if (_state == SubmitToElectrician) 106 | { 107 | if (_electrician.checkOnStatus()) 108 | { 109 | _state++; 110 | _technician.submitNetworkRequest(); 111 | cout << "submitted to MISS - " << _count << 112 | " phone calls so far" << '\n'; 113 | } 114 | } 115 | else if (_state == SubmitToTechnician) 116 | { 117 | if (_technician.checkOnStatus()){ 118 | return 1; 119 | } 120 | } 121 | return 0; 122 | } 123 | int getNumberOfCalls() 124 | { 125 | return _count; 126 | } 127 | private: 128 | enum States 129 | { 130 | Received, SubmitToEngineer, SubmitToElectrician, SubmitToTechnician 131 | }; 132 | int _state, _count; 133 | FacilitiesDepartment _engineer; 134 | ElectricianUnion _electrician; 135 | MissDepartment _technician; 136 | }; 137 | 138 | //auto main() -> int 139 | //{ 140 | // FacilitiesFacade facade; 141 | // facade.submitNetworkRequest(); 142 | // while (!facade.checkOnStatus()){ 143 | // ; 144 | // } 145 | // cout << "job completed after " << facade.getNumberOfCalls() << 146 | // " phone calls" << '\n'; 147 | // getchar(); 148 | //} -------------------------------------------------------------------------------- /cppplaydesignpatterns/factorymethod.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h" 2 | 3 | using namespace std; 4 | 5 | const double PI4 = 3.14159265359 / 4; 6 | 7 | class Point 8 | { 9 | Point(const float x, const float y) : x{ x }, y{ y } {} 10 | public: 11 | float x, y; 12 | friend std::ostream& operator<<(std::ostream& os, const Point& obj) 13 | { 14 | return os << "x: " << obj.x << " y: " << obj.y << '\n'; 15 | } 16 | friend class PointFactory; 17 | }; 18 | 19 | class PointFactory 20 | { 21 | public: 22 | static Point NewCartesian(const float x, const float y) 23 | { 24 | return{ x, y }; 25 | } 26 | 27 | static Point NewPolar(const float r, const float theta) 28 | { 29 | return{ r * cos(theta), r * sin(theta) }; 30 | } 31 | }; 32 | 33 | 34 | //auto main() -> int 35 | //{ 36 | // auto c = PointFactory::NewCartesian(0, 1); 37 | // auto p = PointFactory::NewPolar(1, PI4); 38 | // cout << c << '\n'; 39 | // cout << p << '\n'; 40 | // getchar(); 41 | //} -------------------------------------------------------------------------------- /cppplaydesignpatterns/flyweight.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h" 2 | 3 | using namespace std; 4 | using namespace boost; 5 | 6 | typedef uint32_t key; 7 | 8 | struct User 9 | { 10 | User(const string& first_name, const string& last_name) : 11 | first_name(add(first_name)), last_name(add(last_name)) 12 | { 13 | } 14 | const string& get_first_name() 15 | { 16 | return names.left.find(first_name)->second; 17 | } 18 | const string& get_last_name() 19 | { 20 | return names.left.find(last_name)->second; 21 | } 22 | 23 | friend ostream& operator<<(ostream& os, User& obj) 24 | { 25 | return os 26 | << "first name: " << obj.first_name << " " << obj.get_first_name() 27 | << " last name: " << obj.last_name << " " << obj.get_last_name(); 28 | } 29 | 30 | protected: 31 | static bimap names; 32 | static int seed; 33 | key add(string s) 34 | { 35 | auto it = names.right.find(s); 36 | if (it == names.right.end()) 37 | { 38 | key id = ++seed; 39 | names.insert(bimap::value_type(seed, s)); 40 | return id; 41 | } 42 | return it->second; 43 | } 44 | key first_name, last_name; 45 | }; 46 | 47 | int User::seed = 0; 48 | bimap User::names{}; 49 | 50 | //auto main() -> int 51 | //{ 52 | // User hanna_fox{ "Hanna", "Fox" }; 53 | // User maria_fox{ "Maria", "Fox" }; 54 | // User sophia_fox{ "Sophia", "Fox" }; 55 | // 56 | // cout << "Hanna " << hanna_fox << '\n'; 57 | // cout << "Maria " << maria_fox << '\n'; 58 | // cout << "Sophia " << sophia_fox << '\n'; 59 | // getchar(); 60 | //} 61 | -------------------------------------------------------------------------------- /cppplaydesignpatterns/headers.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include -------------------------------------------------------------------------------- /cppplaydesignpatterns/hottechnology.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "headers.h" 3 | using namespace std; 4 | 5 | struct HT 6 | { 7 | virtual void b(int e) = 0; 8 | }; 9 | 10 | struct A : HT 11 | { 12 | void b(int e) 13 | { 14 | cout << "a -> d -> i " << e << '\n'; 15 | } 16 | }; 17 | 18 | struct X : HT 19 | { 20 | void b(int e) 21 | { 22 | cout << "c -> mc -> a " << e << '\n'; 23 | } 24 | }; 25 | 26 | 27 | -------------------------------------------------------------------------------- /cppplaydesignpatterns/interpreter.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h" 2 | using namespace std; 3 | 4 | class Thousand; 5 | class Hundred; 6 | class Ten; 7 | class One; 8 | 9 | class RomanInterpreter 10 | { 11 | public: 12 | RomanInterpreter(); 13 | RomanInterpreter(int){} 14 | //~RomanInterpreter(); 15 | int interpret(char*); 16 | virtual void interpret(char *input, int &total){ 17 | int index; 18 | index = 0; 19 | if (!strncmp(input, nine(), 2)) 20 | { 21 | total += 9 * multiplier(); 22 | index += 2; 23 | } 24 | else if (!strncmp(input, four(), 2)) 25 | { 26 | total += 4 * multiplier(); 27 | index += 2; 28 | } 29 | else 30 | { 31 | if (input[0] == five()) 32 | { 33 | total += 5 * multiplier(); 34 | index = 1; 35 | } 36 | else 37 | { 38 | index = 0; 39 | } 40 | for (int end = index + 3; index < end; index++) 41 | { 42 | if (input[index] == one()) 43 | { 44 | total += 1 * multiplier(); 45 | } 46 | else 47 | { 48 | break; 49 | } 50 | } 51 | } 52 | strcpy(input, &(input[index])); 53 | } 54 | protected: 55 | virtual char one() { return 0; } 56 | virtual char *four() { return 0; } 57 | virtual char five() { return 0; } 58 | virtual char *nine() { return 0; } 59 | virtual int multiplier(){ return 0; } 60 | private: 61 | RomanInterpreter *thousands; 62 | RomanInterpreter *hundreds; 63 | RomanInterpreter *tens; 64 | RomanInterpreter *ones; 65 | }; 66 | class Thousand : public RomanInterpreter 67 | { 68 | public: 69 | Thousand(int) :RomanInterpreter(1){} 70 | protected: 71 | char one() 72 | { 73 | return 'M'; 74 | } 75 | char *four() 76 | { 77 | return ""; 78 | } 79 | char five() 80 | { 81 | return '\0'; 82 | } 83 | char *nine() 84 | { 85 | return ""; 86 | } 87 | int multiplier() 88 | { 89 | return 1000; 90 | } 91 | }; 92 | class Hundred : public RomanInterpreter 93 | { 94 | public: 95 | Hundred(int) : RomanInterpreter(1){} 96 | protected: 97 | char one() 98 | { 99 | return 'C'; 100 | } 101 | char *four() 102 | { 103 | return "CD"; 104 | } 105 | char five() 106 | { 107 | return 'D'; 108 | } 109 | char *nine() 110 | { 111 | return "CM"; 112 | } 113 | int multiplier() 114 | { 115 | return 100; 116 | } 117 | }; 118 | class Ten : public RomanInterpreter 119 | { 120 | public: 121 | Ten(int) : RomanInterpreter(1){} 122 | protected: 123 | char one() 124 | { 125 | return 'X'; 126 | } 127 | char *four() 128 | { 129 | return "XL"; 130 | } 131 | char five() 132 | { 133 | return 'L'; 134 | } 135 | char *nine() 136 | { 137 | return "XC"; 138 | } 139 | int multiplier() 140 | { 141 | return 10; 142 | } 143 | }; 144 | class One : public RomanInterpreter 145 | { 146 | public: 147 | One(int) : RomanInterpreter(1){} 148 | protected: 149 | char one() 150 | { 151 | return 'I'; 152 | } 153 | char *four() 154 | { 155 | return "IV"; 156 | } 157 | char five() 158 | { 159 | return 'V'; 160 | } 161 | char *nine() 162 | { 163 | return "IX"; 164 | } 165 | int multiplier() 166 | { 167 | return 1; 168 | } 169 | }; 170 | RomanInterpreter::RomanInterpreter() 171 | { 172 | thousands = new Thousand(1); 173 | hundreds = new Hundred(1); 174 | tens = new Ten(1); 175 | ones = new One(1); 176 | } 177 | 178 | int RomanInterpreter::interpret(char* input) 179 | { 180 | int total = 0; 181 | thousands->interpret(input, total); 182 | hundreds->interpret(input, total); 183 | tens->interpret(input, total); 184 | ones->interpret(input, total); 185 | if (strcmp(input, "")){ 186 | return 0; 187 | } 188 | return total; 189 | } 190 | 191 | //auto main() -> int 192 | //{ 193 | // RomanInterpreter interpreter; 194 | // char input[20]; 195 | // cout << "Enter Roman Numeral: "; 196 | // while (cin >> input) 197 | // { 198 | // cout << " interpretation is " << interpreter.interpret(input) << '\n'; 199 | // cout << "Enter Roman Numeral: "; 200 | // } 201 | //} 202 | -------------------------------------------------------------------------------- /cppplaydesignpatterns/iterator.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h" 2 | using namespace std; 3 | 4 | class Stack 5 | { 6 | int items[10]; 7 | int sp; 8 | public: 9 | friend class StackIter; 10 | Stack() 11 | { 12 | sp = -1; 13 | } 14 | void push(int in) 15 | { 16 | items[++sp] = in; 17 | } 18 | int pop() 19 | { 20 | return items[sp--]; 21 | } 22 | bool IsEmpty() 23 | { 24 | return (sp == -1); 25 | } 26 | StackIter *createIterator()const; 27 | }; 28 | class StackIter 29 | { 30 | const Stack *stk; 31 | int index; 32 | public: 33 | StackIter(const Stack *s) 34 | { 35 | stk = s; 36 | } 37 | void first() 38 | { 39 | index = 0; 40 | } 41 | void next() 42 | { 43 | index++; 44 | } 45 | bool isDone() 46 | { 47 | return index == stk->sp + 1; 48 | } 49 | int currentItem() 50 | { 51 | return stk->items[index]; 52 | } 53 | }; 54 | 55 | StackIter *Stack::createIterator() const 56 | { 57 | return new StackIter(this); 58 | } 59 | 60 | bool operator == (const Stack &l, const Stack &r) 61 | { 62 | StackIter *itl = l.createIterator(); 63 | StackIter *itr = r.createIterator(); 64 | 65 | for (itl->first(), itr->first(); !itl->isDone(); itl->next(), itr->next()) 66 | if (itl->currentItem() != itr->currentItem()){ 67 | break; 68 | } 69 | bool ans = itl->isDone() && itr->isDone(); 70 | delete itr; 71 | delete itl; 72 | return ans; 73 | } 74 | //auto main() -> int 75 | //{ 76 | // Stack s1; 77 | // for (int i = 1; i < 5; i++) 78 | // { 79 | // s1.push(i); 80 | // } 81 | // Stack s2(s1), s3(s1), s4(s1), s5(s1); 82 | // s3.pop(); 83 | // s5.pop(); 84 | // s4.push(2); 85 | // s5.push(9); 86 | // cout << "1 == 2 is " << (s1 == s2) << '\n'; 87 | // cout << "1 == 3 is " << (s1 == s3) << '\n'; 88 | // cout << "1 == 4 is " << (s1 == s4) << '\n'; 89 | // cout << "1 == 5 is " << (s1 == s5) << '\n'; 90 | // 91 | // getchar(); 92 | //} -------------------------------------------------------------------------------- /cppplaydesignpatterns/mediator.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h" 2 | 3 | using namespace std; 4 | 5 | class FileSelectionDialog; 6 | 7 | class Widget 8 | { 9 | public: 10 | Widget(FileSelectionDialog *mediator, char *name) 11 | { 12 | _mediator = mediator; 13 | strcpy(_name, name); 14 | } 15 | virtual void changed(); 16 | virtual void updateWidget() = 0; 17 | virtual void queryWidget() = 0; 18 | protected: 19 | char _name[20]; 20 | private: 21 | FileSelectionDialog * _mediator; 22 | }; 23 | 24 | class List : public Widget 25 | { 26 | public: 27 | List(FileSelectionDialog *dir, char *name) : Widget(dir, name){} 28 | void queryWidget() 29 | { 30 | cout << " " << _name << " list queried " << '\n'; 31 | } 32 | void updateWidget() 33 | { 34 | cout << " " << _name << " list updated " << '\n'; 35 | } 36 | }; 37 | 38 | class Edit : public Widget 39 | { 40 | public: 41 | Edit(FileSelectionDialog *dir, char *name) : Widget(dir, name){} 42 | void queryWidget() 43 | { 44 | cout << " " << _name << " edit queried " << '\n'; 45 | } 46 | void updateWidget() 47 | { 48 | cout << " " << _name << " edit updated " << '\n'; 49 | } 50 | }; 51 | 52 | class FileSelectionDialog 53 | { 54 | public: 55 | enum Widgets 56 | { 57 | FilterEdit, DirList, FileList, SelectionEdit 58 | }; 59 | FileSelectionDialog() 60 | { 61 | _components[FilterEdit] = new Edit(this, "filter"); 62 | _components[DirList] = new List(this, "dir"); 63 | _components[FileList] = new List(this, "file"); 64 | _components[SelectionEdit] = new Edit(this, "selection"); 65 | } 66 | virtual ~FileSelectionDialog(); 67 | void handleEvent(int which) 68 | { 69 | _components[which]->changed(); 70 | } 71 | virtual void widgetChanged(Widget *theChangedWidget) 72 | { 73 | if (theChangedWidget == _components[FilterEdit]) 74 | { 75 | _components[FilterEdit]->queryWidget(); 76 | _components[DirList]->updateWidget(); 77 | _components[FileList]->updateWidget(); 78 | _components[SelectionEdit]->updateWidget(); 79 | } 80 | else if (theChangedWidget == _components[DirList]) 81 | { 82 | _components[DirList]->queryWidget(); 83 | _components[FileList]->updateWidget(); 84 | _components[FilterEdit]->updateWidget(); 85 | _components[SelectionEdit]->updateWidget(); 86 | } 87 | else if (theChangedWidget == _components[FileList]) 88 | { 89 | _components[FileList]->queryWidget(); 90 | _components[SelectionEdit]->updateWidget(); 91 | } 92 | else if (theChangedWidget == _components[SelectionEdit]) 93 | { 94 | _components[SelectionEdit]->queryWidget(); 95 | cout << " file opened" << '\n'; 96 | } 97 | } 98 | private: 99 | Widget * _components[4]; 100 | }; 101 | FileSelectionDialog::~FileSelectionDialog() 102 | { 103 | for (int i = 0; i < 4; i++) 104 | { 105 | delete _components[i]; 106 | } 107 | } 108 | void Widget::changed() 109 | { 110 | _mediator->widgetChanged(this); 111 | } 112 | 113 | //auto main() -> int 114 | //{ 115 | // FileSelectionDialog fileDialog; 116 | // int i; 117 | // cout << "Exit[0], Filter[1], Dir[2], File[3], Selection[4]: "; 118 | // cin >> i; 119 | // while (i) 120 | // { 121 | // fileDialog.handleEvent(i - 1); 122 | // cout << "Exit[0], Filter[1], Dir[2], File[3], Selection[4]: "; 123 | // cin >> i; 124 | // } 125 | //} -------------------------------------------------------------------------------- /cppplaydesignpatterns/memento.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h" 2 | 3 | using namespace std; 4 | 5 | class Memento 6 | { 7 | int balance; 8 | public: 9 | Memento(const int balance) : balance(balance){} 10 | friend class BankAccount; 11 | friend class BankAccount2; 12 | }; 13 | 14 | class BankAccount 15 | { 16 | int balance = 0; 17 | vector> changes; 18 | int current; 19 | public: 20 | explicit BankAccount(const int balance) : balance(balance) 21 | { 22 | changes.emplace_back(make_shared(balance)); 23 | current = 0; 24 | } 25 | void restore(shared_ptr& m) 26 | { 27 | if (m) 28 | { 29 | balance = m->balance; 30 | changes.push_back(m); 31 | current = changes.size() - 1; 32 | } 33 | } 34 | shared_ptr deposit(int amount) 35 | { 36 | balance += amount; 37 | auto m = make_shared(balance); 38 | changes.push_back(m); 39 | ++current; 40 | return m; 41 | } 42 | shared_ptr undo() 43 | { 44 | if (current > 0) 45 | { 46 | --current; 47 | auto m = changes[current]; 48 | balance = m->balance; 49 | return m; 50 | } 51 | return{}; 52 | } 53 | shared_ptr redo() 54 | { 55 | if (current + 1 < changes.size()) 56 | { 57 | ++current; 58 | auto m = changes[current]; 59 | balance = m->balance; 60 | return m; 61 | } 62 | return{}; 63 | } 64 | friend ostream& operator <<(ostream& os, const BankAccount& obj) 65 | { 66 | return os << "balance " << obj.balance; 67 | } 68 | }; 69 | 70 | 71 | //auto main() -> int 72 | //{ 73 | // BankAccount ba{ 1000 }; 74 | // ba.deposit(500); 75 | // ba.deposit(250); 76 | // cout << ba << '\n'; //1750 77 | // ba.undo(); 78 | // cout << ba << '\n'; //1500 79 | // ba.undo(); 80 | // cout << ba << '\n'; //1000 81 | // ba.redo(); 82 | // cout << ba << '\n'; //1500 83 | // ba.redo(); 84 | // cout << ba << '\n'; //1750 85 | // getchar(); 86 | //} -------------------------------------------------------------------------------- /cppplaydesignpatterns/observer.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h" 2 | #include 3 | using namespace std; 4 | using namespace boost; 5 | 6 | struct Technology; 7 | 8 | struct TechnologyListener 9 | { 10 | virtual ~TechnologyListener() = default; 11 | virtual void TechnologyChanged(Technology& t, 12 | const string& property_name, const any new_value) = 0; 13 | }; 14 | 15 | static mutex mtx; 16 | 17 | struct Technology 18 | { 19 | explicit Technology(const int power) : power(power){} 20 | virtual int GetPower() const{ 21 | return power; 22 | } 23 | virtual void SetPower(const int power){ 24 | if (this->power == power){ return; } 25 | 26 | auto old_p_s = GetPassesStandards(); 27 | this->power = power; 28 | Notify("power", this->power); 29 | auto new_p_s = GetPassesStandards(); 30 | if (old_p_s != new_p_s){ 31 | Notify("take", new_p_s); 32 | } 33 | } 34 | 35 | bool GetPassesStandards()const { 36 | return power >= 100; 37 | } 38 | 39 | void Subscribe(TechnologyListener* tl) 40 | { 41 | lock_guard guard{ mtx }; 42 | if (find(std::begin(listeners), std::end(listeners), tl) == std::end(listeners)) { 43 | listeners.push_back(tl); 44 | } 45 | } 46 | void Unsubscribe(TechnologyListener* tl){ 47 | lock_guard guard{ mtx }; 48 | for (auto it = listeners.begin(); it != listeners.end(); ++it){ 49 | if (*it == tl){ 50 | *it = nullptr; 51 | } 52 | } 53 | } 54 | void Notify(const string& property_name, const any new_value){ 55 | lock_guard guard{ mtx }; 56 | for (const auto listener : listeners){ 57 | if (listener){ 58 | listener->TechnologyChanged(*this, property_name, new_value); 59 | listeners.erase(remove(listeners.begin(), listeners.end(), nullptr), 60 | listeners.end()); 61 | } 62 | } 63 | } 64 | private: 65 | int power; 66 | vector listeners; 67 | }; 68 | 69 | struct WickedListener : TechnologyListener 70 | { 71 | void TechnologyChanged(Technology& t, const string& property_name, const any new_value) 72 | { 73 | t.Unsubscribe(this); 74 | } 75 | }; 76 | 77 | struct ConsoleListener : TechnologyListener 78 | { 79 | void TechnologyChanged(Technology& t, const string& property_name, const any new_value) 80 | { 81 | cout << "technologies " << property_name << " has changed to "; 82 | if (property_name == "power") 83 | { 84 | cout << any_cast(new_value); 85 | } 86 | else if (property_name == "take"){ 87 | cout << any_cast(new_value); 88 | } 89 | cout << '\n'; 90 | } 91 | }; 92 | 93 | //auto main() -> int 94 | //{ 95 | // Technology v8{ 98 }; 96 | // ConsoleListener cl; 97 | // //WickedListener cl; 98 | // v8.Subscribe(&cl); 99 | // v8.Subscribe(&cl); 100 | // v8.SetPower(99); 101 | // v8.SetPower(100); 102 | // v8.Unsubscribe(&cl); 103 | // v8.SetPower(101); 104 | //} -------------------------------------------------------------------------------- /cppplaydesignpatterns/observerboost.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h" 2 | 3 | using namespace std; 4 | using namespace boost; 5 | 6 | template 7 | struct INotifyPropertyChanged 8 | { 9 | virtual ~INotifyPropertyChanged() = default; 10 | signals2::signal PropertyChanged; 11 | }; 12 | 13 | struct SexyLady : INotifyPropertyChanged 14 | { 15 | explicit SexyLady(const int shoesize) : shoesize(shoesize) 16 | { 17 | } 18 | virtual int GetShoeSize() 19 | { 20 | return shoesize; 21 | } 22 | 23 | virtual void SetShoeSize(const int shoesize) 24 | { 25 | if (this->shoesize == shoesize){ return; } 26 | this->shoesize = shoesize; 27 | PropertyChanged(*this, "shoesize"); 28 | } 29 | private: 30 | int shoesize; 31 | }; 32 | 33 | //auto main() -> int 34 | //{ 35 | // SexyLady S{ 37 }; 36 | // S.PropertyChanged.connect([](SexyLady&, const string& property_name) 37 | // { 38 | // cout << property_name << " has changed " << '\n'; 39 | // }); 40 | // S.SetShoeSize(38); 41 | //} 42 | 43 | 44 | -------------------------------------------------------------------------------- /cppplaydesignpatterns/prototype.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h" 2 | 3 | using namespace std; 4 | 5 | class MA 6 | { 7 | public: 8 | virtual MA* clone() = 0; 9 | virtual void collect_data() = 0; 10 | }; 11 | class Factory 12 | { 13 | public: 14 | static MA* make_ma(int selection); 15 | private: 16 | static MA* s_prototypes[4]; 17 | }; 18 | 19 | class CA0 : public MA 20 | { 21 | MA* clone() { return new CA0; } 22 | void collect_data() 23 | { 24 | cout << "CA0: collect data memory 0\n"; 25 | } 26 | }; 27 | class CA1 : public MA 28 | { 29 | MA* clone() { return new CA1; } 30 | void collect_data() 31 | { 32 | cout << "CA1: collect data memory 1\n"; 33 | } 34 | }; 35 | class CA2 : public MA 36 | { 37 | MA* clone() { return new CA2; } 38 | void collect_data() 39 | { 40 | cout << "CA2: collect data memory2\n"; 41 | } 42 | }; 43 | MA* Factory::s_prototypes[] = { 0, new CA0, new CA1, new CA2 }; 44 | MA* Factory::make_ma(int selection){ return s_prototypes[selection]->clone(); } 45 | 46 | //auto main() -> int 47 | //{ 48 | // vector roles; 49 | // int selection; 50 | // 51 | // while (true) 52 | // { 53 | // cout << "CA0(1), CA1(2), CA2(3), Launch(0): "; 54 | // cin >> selection; 55 | // if (selection == 0) 56 | // { 57 | // break; 58 | // } 59 | // roles.push_back(Factory::make_ma(selection)); 60 | // 61 | // for (int i = 0; i < roles.size(); i++) 62 | // { 63 | // roles[i]->collect_data(); 64 | // } 65 | // for (int i = 0; i < roles.size(); i++) 66 | // { 67 | // delete roles[i]; 68 | // } 69 | // } 70 | // getchar(); 71 | //} 72 | -------------------------------------------------------------------------------- /cppplaydesignpatterns/singleton.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h" 2 | using namespace std; 3 | 4 | class GlobalClass 5 | { 6 | int i_value; 7 | static GlobalClass *s_instance; 8 | GlobalClass(int d = 1) 9 | { 10 | i_value = d; 11 | } 12 | public: 13 | int get_value() 14 | { 15 | return i_value; 16 | } 17 | void set_value(int d) 18 | { 19 | i_value = d; 20 | } 21 | static GlobalClass *instance() 22 | { 23 | if (!s_instance) 24 | { 25 | s_instance = new GlobalClass; 26 | } 27 | return s_instance; 28 | } 29 | }; 30 | 31 | GlobalClass *GlobalClass::s_instance = 0; 32 | 33 | void a(void) 34 | { 35 | GlobalClass::instance()->set_value(10); 36 | cout << "a: global_ptr is " << GlobalClass::instance()->get_value() << '\n'; 37 | } 38 | 39 | void b(void) 40 | { 41 | GlobalClass::instance()->set_value(100); 42 | cout << "b: global_ptr is " << GlobalClass::instance()->get_value() << '\n'; 43 | } 44 | 45 | 46 | //auto main() -> int 47 | //{ 48 | // cout << "m: global_ptr is " << GlobalClass::instance()->get_value() << '\n'; 49 | // a(); 50 | // b(); 51 | // getchar(); 52 | //} 53 | 54 | -------------------------------------------------------------------------------- /cppplaydesignpatterns/state1.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include "headers.h" 3 | using namespace std; 4 | enum class State { 5 | OffHook, 6 | Connecting, 7 | Connected, 8 | OnHold 9 | }; 10 | inline ostream& operator<<(ostream& os, const State& s) 11 | { 12 | switch (s) 13 | { 14 | case::State::OffHook: 15 | os << "off the hook"; 16 | break; 17 | case::State::Connecting: 18 | os << "connecting"; 19 | break; 20 | case::State::Connected: 21 | os << "connected"; 22 | break; 23 | case::State::OnHold: 24 | os << "on hold"; 25 | break; 26 | } 27 | return os; 28 | } 29 | 30 | enum class Trigger { 31 | CallDialed, 32 | HungUp, 33 | CallConnected, 34 | PlacedOnHold, 35 | TakenOffHold, 36 | LeftMessage 37 | }; 38 | 39 | inline ostream& operator<<(ostream& os, const Trigger& t) 40 | { 41 | switch (t) 42 | { 43 | case::Trigger::CallDialed: 44 | os << "call dialed"; 45 | break; 46 | case::Trigger::HungUp: 47 | os << "hung up"; 48 | break; 49 | case::Trigger::CallConnected: 50 | os << "call connected"; 51 | break; 52 | case::Trigger::TakenOffHold: 53 | os << "taken off hold"; 54 | break; 55 | case::Trigger::LeftMessage: 56 | os << "get it done"; 57 | break; 58 | default: break; 59 | } 60 | return os; 61 | } 62 | 63 | //auto main() -> int 64 | //{ 65 | // map>> rules; 66 | // rules[State::OffHook] = { 67 | // { 68 | // Trigger::CallDialed, State::Connecting 69 | // } 70 | // }; 71 | // rules[State::Connecting] = { 72 | // { 73 | // Trigger::HungUp, State::OffHook 74 | // }, 75 | // { 76 | // Trigger::CallConnected, State::Connected 77 | // } 78 | // }; 79 | // rules[State::Connected] = { 80 | // { 81 | // Trigger::LeftMessage, State::OffHook 82 | // }, 83 | // { 84 | // Trigger::HungUp, State::OffHook 85 | // }, 86 | // { 87 | // Trigger::PlacedOnHold, State::OnHold 88 | // } 89 | // }; 90 | // rules[State::OnHold] = { 91 | // { 92 | // Trigger::TakenOffHold, State::Connected 93 | // }, 94 | // { 95 | // Trigger::HungUp, State::OffHook 96 | // } 97 | // }; 98 | // 99 | // State currentState{ State::OffHook }; 100 | // while (true) 101 | // { 102 | // cout << "phone is currently " << currentState << '\n'; 103 | // select_trigger: 104 | // cout << "select a trigger: " << '\n'; 105 | // 106 | // int i = 0; 107 | // for (auto item : rules[currentState]) 108 | // { 109 | // cout << i++ << ". " << item.first << '\n'; 110 | // } 111 | // int input; 112 | // cin >> input; 113 | // if (input < 1 || (input + 1) > rules[currentState].size()) 114 | // { 115 | // cout << "incorrect option. give it another shot.\n"; 116 | // goto select_trigger; 117 | // } 118 | // currentState = rules[currentState][input].second; 119 | // } 120 | // cout << "done using the phone" << '\n'; 121 | //} 122 | -------------------------------------------------------------------------------- /cppplaydesignpatterns/state2.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h" 2 | using namespace std; 3 | namespace msm = boost::msm; 4 | namespace mpl = boost::mpl; 5 | using namespace msm::front; 6 | 7 | vector state_names{"off hook","connecting","connected","onhold","killed"}; 8 | struct CallDialed {}; 9 | struct HungUp {}; 10 | struct CallConnected {}; 11 | struct PlacedOnHold {}; 12 | struct TakenOffHold {}; 13 | struct LeftMessage {}; 14 | struct PhoneThrownAway {}; 15 | struct PhoneStateMachine : state_machine_def 16 | { 17 | struct OffHook : state<> {}; 18 | struct Connecting : state<> {}; 19 | struct Connected : state<> {}; 20 | struct OnHold : state<> {}; 21 | struct PhoneKilled : state<> {}; 22 | struct transition_table : mpl::vector< 23 | Row, 24 | Row, 25 | Row, 26 | Row> {}; 27 | typedef OffHook initial_state; 28 | }; 29 | 30 | //auto main() -> int 31 | //{ 32 | // msm::back::state_machine phone; 33 | // auto info = [&]() 34 | // { 35 | // auto i = phone.current_state()[0]; 36 | // cout << "phone is currently " << state_names[i] << '\n'; 37 | // 38 | // }; 39 | // info(); 40 | // phone.process_event(CallDialed{}); 41 | // info(); 42 | //} 43 | 44 | -------------------------------------------------------------------------------- /cppplaydesignpatterns/strategy_dynamic.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h" 2 | 3 | using namespace std; 4 | 5 | enum class OutputFormat 6 | { 7 | HTML, 8 | Markdown 9 | }; 10 | 11 | struct ListStrategy 12 | { 13 | virtual ~ListStrategy() = default; 14 | virtual void add_list_item(ostringstream& oss, const string& item) = 0; 15 | virtual void start(ostringstream& oss) = 0; 16 | virtual void end(ostringstream& oss) = 0; 17 | }; 18 | 19 | struct MarkdownListStrategy : ListStrategy 20 | { 21 | void start(ostringstream& oss) override 22 | { 23 | } 24 | 25 | void end(ostringstream& oss) override 26 | { 27 | } 28 | 29 | void add_list_item(ostringstream& oss, const string& item) override 30 | { 31 | oss << " * " << item << endl; 32 | } 33 | }; 34 | 35 | struct HtmlListStrategy : ListStrategy 36 | { 37 | void start(ostringstream& oss) override 38 | { 39 | oss << "
    " << endl; 40 | } 41 | 42 | void end(ostringstream& oss) override 43 | { 44 | oss << "
" << endl; 45 | } 46 | 47 | void add_list_item(ostringstream& oss, const string& item) override 48 | { 49 | oss << "
  • " << item << "
  • " << endl; 50 | } 51 | }; 52 | 53 | struct TextProcessor 54 | { 55 | void clear() 56 | { 57 | oss.str(""); 58 | oss.clear(); 59 | } 60 | void append_list(const vector items) 61 | { 62 | list_strategy->start(oss); 63 | for (auto& item : items) 64 | list_strategy->add_list_item(oss, item); 65 | list_strategy->end(oss); 66 | } 67 | 68 | void set_output_format(OutputFormat format) 69 | { 70 | switch (format) 71 | { 72 | case OutputFormat::Markdown: 73 | list_strategy = make_unique(); 74 | break; 75 | case OutputFormat::HTML: 76 | list_strategy = make_unique(); 77 | break; 78 | default: 79 | throw runtime_error("unsupported strategy."); 80 | } 81 | } 82 | string str() const { return oss.str(); } 83 | private: 84 | ostringstream oss; 85 | unique_ptr list_strategy; 86 | }; 87 | 88 | 89 | 90 | //auto main() -> int 91 | //{ 92 | // TextProcessor tp; 93 | // tp.set_output_format(OutputFormat::Markdown); 94 | // tp.append_list({ "a", "b", "c" }); 95 | // cout << tp.str() << endl; 96 | // tp.clear(); 97 | // tp.set_output_format(OutputFormat::HTML); 98 | // tp.append_list({ "a", "b", "c" }); 99 | // cout << tp.str() << endl; 100 | //} 101 | 102 | 103 | 104 | -------------------------------------------------------------------------------- /cppplaydesignpatterns/template.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h" 2 | using namespace std; 3 | 4 | class Base 5 | { 6 | void a(){ 7 | cout << "a "; 8 | } 9 | void c(){ 10 | cout << "c "; 11 | } 12 | void e(){ 13 | cout << "e "; 14 | } 15 | virtual void ph1() = 0; 16 | virtual void ph2() = 0; 17 | public: 18 | void execute(){ 19 | a(); 20 | ph1(); 21 | c(); 22 | ph2(); 23 | e(); 24 | } 25 | }; 26 | 27 | class One : public Base 28 | { 29 | void ph1(){ 30 | cout << "b "; 31 | } 32 | void ph2(){ 33 | cout << "d "; 34 | } 35 | }; 36 | class Two : public Base 37 | { 38 | void ph1(){ 39 | cout << "2 "; 40 | } 41 | void ph2(){ 42 | cout << "4 "; 43 | } 44 | }; 45 | 46 | 47 | //auto main() -> int 48 | //{ 49 | // Base *array[] = 50 | // { 51 | // &One(), &Two() 52 | // }; 53 | // for (int i = 0; i < 2; i++){ 54 | // array[i]->execute(); 55 | // cout << '\n'; 56 | // } 57 | //} -------------------------------------------------------------------------------- /cppplaydesignpatterns/virtualproxy.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h" 2 | 3 | using namespace std; 4 | 5 | struct Technology 6 | { 7 | virtual ~Technology() = default; 8 | virtual void increase(int power) = 0; 9 | virtual void decrease(int power) = 0; 10 | }; 11 | 12 | struct NewTechnology : Technology 13 | { 14 | explicit NewTechnology(const int status) : status(status){} 15 | 16 | void increase(int power) override 17 | { 18 | status += power; 19 | } 20 | void decrease(int power) override 21 | { 22 | status -= power; 23 | } 24 | friend ostream& operator <<(ostream& os, const NewTechnology& obj) 25 | { 26 | return os << "status: " << obj.status; 27 | } 28 | private: 29 | int status; 30 | }; 31 | 32 | void smart_pointers() 33 | { 34 | Technology* t = new NewTechnology{ 100 }; 35 | t->increase(1); 36 | delete t; 37 | 38 | shared_ptr u = make_shared(1000); 39 | u->increase(1); 40 | 41 | NewTechnology* underlying = u.get(); 42 | 43 | cout << *u << '\n'; 44 | } 45 | 46 | struct Image 47 | { 48 | virtual ~Image() = default; 49 | virtual void draw() = 0; 50 | }; 51 | 52 | struct Bitmap : Image 53 | { 54 | Bitmap(const string& fileName) 55 | { 56 | cout << "loading the file from " << fileName << '\n'; 57 | } 58 | void draw() override 59 | { 60 | cout << "draw an image" << '\n'; 61 | } 62 | }; 63 | 64 | struct LazyBitmap : Image 65 | { 66 | LazyBitmap(const string& fileName) : fileName(fileName), bmp(nullptr) 67 | { 68 | } 69 | ~LazyBitmap() 70 | { 71 | delete bmp; 72 | } 73 | void draw() override 74 | { 75 | if (!bmp) { bmp = new Bitmap{ fileName }; } 76 | bmp->draw(); 77 | } 78 | private: 79 | Bitmap* bmp; 80 | string fileName; 81 | }; 82 | 83 | void draw_image(Image& image) 84 | { 85 | cout << "about to draw the image" << '\n'; 86 | image.draw(); 87 | cout << "done drawing the image" << '\n'; 88 | } 89 | 90 | void virtual_proxy() 91 | { 92 | LazyBitmap bmp{ "node.png" }; 93 | draw_image(bmp); draw_image(bmp); 94 | } 95 | 96 | 97 | //auto main() -> int 98 | //{ 99 | // virtual_proxy(); 100 | // //smart_pointers(); 101 | // getchar(); 102 | //} -------------------------------------------------------------------------------- /cppplaydesignpatterns/visitor.cpp: -------------------------------------------------------------------------------- 1 | #include "headers.h" 2 | 3 | using namespace std; 4 | 5 | class Element 6 | { 7 | public: 8 | virtual void accept(class Visitor &v) = 0; 9 | }; 10 | 11 | 12 | class This : public Element 13 | { 14 | public: 15 | void accept(Visitor &v); 16 | string thiss() 17 | { 18 | return "This"; 19 | } 20 | }; 21 | 22 | class That : public Element 23 | { 24 | public: 25 | void accept(Visitor &v); 26 | string that() 27 | { 28 | return "That"; 29 | } 30 | }; 31 | 32 | class TheOther : public Element 33 | { 34 | public: 35 | void accept(Visitor &v); 36 | string theOther() 37 | { 38 | return "TheOther"; 39 | } 40 | }; 41 | 42 | class Visitor 43 | { 44 | public: 45 | virtual void visit(This *e) = 0; 46 | virtual void visit(That *e) = 0; 47 | virtual void visit(TheOther *e) = 0; 48 | }; 49 | 50 | void This::accept(Visitor &v) 51 | { 52 | v.visit(this); 53 | } 54 | 55 | void That::accept(Visitor &v) 56 | { 57 | v.visit(this); 58 | } 59 | 60 | void TheOther::accept(Visitor &v) 61 | { 62 | v.visit(this); 63 | } 64 | 65 | 66 | class UpVisitor : public Visitor 67 | { 68 | void visit(This *e) 69 | { 70 | cout << "do up on " << e->thiss() << '\n'; 71 | } 72 | 73 | void visit(That *e) 74 | { 75 | cout << "do up on " << e->that() << '\n'; 76 | } 77 | 78 | void visit(TheOther *e) 79 | { 80 | cout << "do up on " << e->theOther() << '\n'; 81 | } 82 | }; 83 | 84 | class DownVisitor : public Visitor 85 | { 86 | void visit(This *e) 87 | { 88 | cout << "do down on " << e->thiss() << '\n'; 89 | 90 | } 91 | void visit(That *e) 92 | { 93 | cout << "do down on " << e->that() << '\n'; 94 | } 95 | void visit(TheOther *e) 96 | { 97 | cout << "do down on " << e->theOther() << '\n'; 98 | } 99 | 100 | 101 | }; 102 | 103 | 104 | auto main() -> int 105 | { 106 | Element *list[] = { new This(), new That(), new TheOther() }; 107 | UpVisitor up; DownVisitor down; 108 | for (int i = 0; i < 3; i++) { list[i]->accept(up); } 109 | for (int i = 0; i < 3; i++) { list[i]->accept(down); } 110 | getchar(); 111 | } --------------------------------------------------------------------------------