├── C++ ├── TCPClosed.cpp ├── AbstractFactory │ ├── MazeFactory.cpp │ ├── MazeFactory.h │ └── AbstractFactory.cpp ├── List.h ├── old-Singleton │ ├── a.out │ ├── Singleton.h │ ├── Singleton.cpp │ └── main.cpp ├── Geom.h ├── main.cpp ├── defs.h ├── MazeFactory.h ├── MazeGame.h ├── MazeFactories.h ├── abfactory.cpp ├── tmethod.cpp ├── decorator.cpp ├── flyweight.cpp ├── mediator.cpp ├── MazeParts.h ├── prototype.cpp ├── singleton.cpp ├── adapter.cpp ├── command.cpp ├── facade.cpp ├── state.cpp ├── memento.cpp ├── Foundation.h ├── composite.cpp ├── builder.cpp ├── observer.cpp ├── factorymeth.cpp ├── proxy.cpp ├── interpreter.cpp ├── strategy.cpp ├── chain.cpp ├── visitor.cpp ├── bridge.cpp ├── iterator.cpp └── maze.h ├── .gitignore └── Java ├── manifest.mf ├── nbproject ├── private │ ├── private.properties │ └── private.xml ├── genfiles.properties ├── project.xml └── project.properties ├── test └── designpatterns │ ├── PrototypeTest.java │ ├── FacadeTest.java │ ├── FactoryMethodTest.java │ ├── AdapterTest.java │ ├── DecoratorTest.java │ ├── SingletonTest.java │ ├── ProxyTest.java │ ├── AbstractFactoryTest.java │ ├── InterpreterTest.java │ ├── BridgeTest.java │ ├── CommandTest.java │ ├── BuilderTest.java │ ├── TemplateMethodTest.java │ ├── ObserverTest.java │ ├── MediatorTest.java │ ├── StateTest.java │ ├── FlyweightTest.java │ ├── StrategyTest.java │ ├── VisitorTest.java │ ├── ChainOfResponsibilityTest.java │ ├── MementoTest.java │ ├── CompositeTest.java │ └── IteratorTest.java ├── src └── designpatterns │ ├── FactoryMethod.java │ ├── Singleton.java │ ├── Facade.java │ ├── Flyweight.java │ ├── Iterator.java │ ├── Prototype.java │ ├── Adapter.java │ ├── Strategy.java │ ├── Proxy.java │ ├── Decorator.java │ ├── Memento.java │ ├── AbstractFactory.java │ ├── TemplateMethod.java │ ├── Builder.java │ ├── Composite.java │ ├── Observer.java │ ├── ChainOfResponsibility.java │ ├── Bridge.java │ ├── Command.java │ ├── State.java │ ├── Mediator.java │ ├── Interpreter.java │ └── Visitor.java └── build.xml /C++/TCPClosed.cpp: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | Java/build/* -------------------------------------------------------------------------------- /C++/AbstractFactory/MazeFactory.cpp: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /C++/List.h: -------------------------------------------------------------------------------- 1 | #include "Foundation.h" 2 | -------------------------------------------------------------------------------- /C++/old-Singleton/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/john-bai/DesignPatterns/HEAD/C++/old-Singleton/a.out -------------------------------------------------------------------------------- /Java/manifest.mf: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | X-COMMENT: Main-Class will be added automatically by build 3 | 4 | -------------------------------------------------------------------------------- /C++/Geom.h: -------------------------------------------------------------------------------- 1 | #include "Foundation.h" 2 | Coord min(Coord, Coord); 3 | Coord max(Coord, Coord); 4 | Coord abs(Coord); 5 | int round(Coord); 6 | -------------------------------------------------------------------------------- /Java/nbproject/private/private.properties: -------------------------------------------------------------------------------- 1 | compile.on.save=true 2 | user.properties.file=/Users/jtherrell/.netbeans/6.9/build.properties 3 | -------------------------------------------------------------------------------- /C++/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main (int argc, char * const argv[]) { 4 | // insert code here... 5 | std::cout << "Hello, World!\n"; 6 | return 0; 7 | } 8 | -------------------------------------------------------------------------------- /Java/nbproject/private/private.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /C++/defs.h: -------------------------------------------------------------------------------- 1 | #ifndef defs_h 2 | #define defs_h 3 | 4 | #define Implementation1 1; 5 | //typedef int bool; 6 | //const int true = 1; 7 | //const int false = 0; 8 | class istream; 9 | class ostream; 10 | 11 | typedef float Coord; 12 | 13 | 14 | #endif 15 | -------------------------------------------------------------------------------- /C++/old-Singleton/Singleton.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Singleton.h 3 | * DesignPatterns 4 | * 5 | * Created by John Therrell on 1/30/11. 6 | * 7 | */ 8 | class Singleton { 9 | public: 10 | static Singleton* getInstance(); 11 | void addToFoo(int); 12 | int getFoo(); 13 | protected: 14 | Singleton(); 15 | private: 16 | static Singleton* s_instance; 17 | int foo; 18 | }; -------------------------------------------------------------------------------- /C++/AbstractFactory/MazeFactory.h: -------------------------------------------------------------------------------- 1 | class MazeFactory { 2 | public: 3 | MazeFactory(); 4 | /* 5 | */ 6 | virtual Maze* MakeMaze() const 7 | { return new Maze; } 8 | virtual Wall* MakeWall() const 9 | { return new Wall; } 10 | virtual Room* MakeRoom(int n) const 11 | { return new Room(n); } 12 | virtual Door* MakeDoor(Room* r1, Room* r2) const 13 | { return new Door(r1, r2); } 14 | }; -------------------------------------------------------------------------------- /Java/nbproject/genfiles.properties: -------------------------------------------------------------------------------- 1 | build.xml.data.CRC32=e45ff444 2 | build.xml.script.CRC32=b5ad1354 3 | build.xml.stylesheet.CRC32=28e38971@1.38.2.45 4 | # This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. 5 | # Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. 6 | nbproject/build-impl.xml.data.CRC32=e45ff444 7 | nbproject/build-impl.xml.script.CRC32=cf489b80 8 | nbproject/build-impl.xml.stylesheet.CRC32=f33e10ff@1.38.2.45 9 | -------------------------------------------------------------------------------- /Java/test/designpatterns/PrototypeTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import org.junit.Test; 9 | import static org.junit.Assert.*; 10 | 11 | /** 12 | * 13 | * @author jtherrell 14 | */ 15 | public class PrototypeTest { 16 | 17 | @Test 18 | public void testSomeMethod() { 19 | House original = new House(8, 10, 2); 20 | House proto = original.clone(); 21 | assertNotSame(original, proto); 22 | } 23 | 24 | } -------------------------------------------------------------------------------- /C++/old-Singleton/Singleton.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Singleton.cpp 3 | * DesignPatterns 4 | * 5 | * Created by John Therrell on 1/30/11. 6 | * 7 | */ 8 | #include "Singleton.h" 9 | 10 | Singleton* Singleton::s_instance = 0; 11 | 12 | Singleton::Singleton() { 13 | foo = 0; 14 | } 15 | 16 | Singleton* Singleton::getInstance () { 17 | if (!s_instance) { 18 | s_instance = new Singleton; 19 | } 20 | return Singleton::s_instance; 21 | } 22 | 23 | void Singleton::addToFoo(int num) { 24 | foo += num; 25 | } 26 | 27 | int Singleton::getFoo() { 28 | return foo; 29 | } -------------------------------------------------------------------------------- /C++/MazeFactory.h: -------------------------------------------------------------------------------- 1 | #ifndef MazeFactory_H 2 | #define MazeFactory_H 3 | class Maze; 4 | class Room; 5 | class Wall; 6 | class Door; 7 | 8 | class MazeFactory { 9 | public: 10 | MazeFactory(); 11 | 12 | #ifndef Singleton 13 | static MazeFactory* Instance(); 14 | #else 15 | static MazeFactory* Instance(); 16 | #endif 17 | virtual Maze* MakeMaze() const; 18 | virtual Wall* MakeWall() const; 19 | virtual Room* MakeRoom(int n) const; 20 | virtual Door* MakeDoor(Room* r1, Room* r2) const; 21 | protected: 22 | static MazeFactory* _instance; 23 | }; 24 | 25 | #endif 26 | -------------------------------------------------------------------------------- /Java/nbproject/project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | org.netbeans.modules.java.j2seproject 4 | 5 | 6 | DesignPatterns 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /Java/test/designpatterns/FacadeTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import org.junit.Test; 9 | import static org.junit.Assert.*; 10 | /** 11 | * 12 | * @author jtherrell 13 | */ 14 | public class FacadeTest { 15 | /** 16 | * Test of getInstance method, of class Singleton. 17 | */ @Test 18 | public void testFacade() { 19 | Log log = new Log(); 20 | Facade facade = new Facade(); 21 | facade.doSomething(log); 22 | String expResult = "ABCD"; 23 | String result = log.toString(); 24 | assertEquals(expResult, result); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Java/src/designpatterns/FactoryMethod.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | /** 9 | * 10 | * @author jtherrell 11 | */ 12 | abstract class Creator { 13 | public Product newProduct(Log log) { 14 | return createProduct(log); 15 | } 16 | abstract protected Product createProduct(Log log); 17 | 18 | } 19 | 20 | class MyCreator extends Creator { 21 | protected Product createProduct(Log log) { 22 | log.append("Created new MyProduct!"); 23 | return new MyProduct(); 24 | } 25 | } 26 | 27 | class Product {} 28 | class MyProduct extends Product {} 29 | -------------------------------------------------------------------------------- /C++/MazeGame.h: -------------------------------------------------------------------------------- 1 | #ifndef MazeGame_H 2 | #define MazeGame_H 3 | 4 | class Maze; 5 | class Wall; 6 | class Door; 7 | class Room; 8 | 9 | class MazeFactory; 10 | class MazeBuilder; 11 | 12 | class MazeGame { 13 | public: 14 | Maze* CreateMaze(); 15 | 16 | Maze* CreateSimpleMaze(); 17 | Maze* CreateMaze(MazeFactory&); 18 | Maze* CreateMaze(MazeBuilder&); 19 | 20 | Maze* CreateComplexMaze (MazeBuilder& builder); 21 | 22 | // factory methods 23 | 24 | virtual Maze* MakeMaze() const; 25 | virtual Room* MakeRoom(int n) const; 26 | virtual Wall* MakeWall() const; 27 | virtual Door* MakeDoor(Room* r1, Room* r2) const; 28 | }; 29 | #endif 30 | -------------------------------------------------------------------------------- /Java/src/designpatterns/Singleton.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | /** 9 | * 10 | * @author jtherrell 11 | */ 12 | public class Singleton 13 | { 14 | private static Singleton s_instance; 15 | private int foo; 16 | 17 | private Singleton() { 18 | foo = 0; 19 | } 20 | 21 | public static Singleton getInstance() { 22 | if (s_instance == null) { 23 | s_instance = new Singleton(); 24 | } 25 | return s_instance; 26 | } 27 | 28 | public void addToFoo(int num) { 29 | foo += num; 30 | } 31 | 32 | public int getFoo() { 33 | return foo; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /C++/MazeFactories.h: -------------------------------------------------------------------------------- 1 | #ifndef BombedMazeFactory_H 2 | #define BombedMazeFactory_H 3 | #include "MazeFactory.h" 4 | 5 | class BombedMazeFactory : public MazeFactory { 6 | public: 7 | BombedMazeFactory(); 8 | virtual Wall* MakeWall() const; 9 | virtual Room* MakeRoom(int n) const; 10 | }; 11 | #endif 12 | #ifndef EnchantedMazeFactory_H 13 | #define EnchantedMazeFactory_H 14 | #include "MazeFactory.h" 15 | class Spell; 16 | class EnchantedMazeFactory : public MazeFactory { 17 | public: 18 | EnchantedMazeFactory(); 19 | 20 | virtual Room* MakeRoom(int n) const; 21 | virtual Door* MakeDoor(Room* r1, Room* r2) const; 22 | 23 | protected: 24 | Spell* CastSpell() const; 25 | }; 26 | #endif 27 | -------------------------------------------------------------------------------- /Java/test/designpatterns/FactoryMethodTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import org.junit.Test; 9 | import static org.junit.Assert.*; 10 | /** 11 | * 12 | * @author jtherrell 13 | */ 14 | public class FactoryMethodTest { 15 | 16 | /** 17 | * Test of getInstance method, of class Singleton. 18 | */ @Test 19 | public void testFactoryMethod() { 20 | Log log = new Log(); 21 | Creator myCreator = new MyCreator(); 22 | myCreator.newProduct(log); 23 | String expResult = "Created new MyProduct!"; 24 | String result = log.toString(); 25 | assertEquals(expResult, result); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Java/test/designpatterns/AdapterTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import org.junit.Test; 9 | import static org.junit.Assert.*; 10 | 11 | /** 12 | * 13 | * @author jtherrell 14 | */ 15 | public class AdapterTest { 16 | 17 | /** 18 | * Test of Adapter class' adherence to the GUIComponent interface. 19 | */ @Test 20 | public void testAdherenceToGUIComponentInterface() { 21 | GUIComponent comp = new TextShapeAdapter(); 22 | String expResult = "java.awt.Rectangle[x=0,y=0,width=10,height=10]"; 23 | String result = comp.boundingBox().toString(); 24 | assertEquals(expResult, result); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Java/src/designpatterns/Facade.java: -------------------------------------------------------------------------------- 1 | package designpatterns; 2 | 3 | /** 4 | * @author jtherrell 5 | */ 6 | class Facade { 7 | public void doSomething(Log log) { 8 | SubsystemClassA.doSomething(log); 9 | SubsystemClassB.doSomething(log); 10 | SubsystemClassC.doSomething(log); 11 | SubsystemClassD.doSomething(log); 12 | } 13 | } 14 | 15 | class SubsystemClassA { 16 | public static void doSomething(Log log){log.append("A");} 17 | } 18 | 19 | class SubsystemClassB { 20 | public static void doSomething(Log log){log.append("B");} 21 | } 22 | 23 | class SubsystemClassC { 24 | public static void doSomething(Log log){log.append("C");} 25 | } 26 | 27 | class SubsystemClassD { 28 | public static void doSomething(Log log){log.append("D");} 29 | } -------------------------------------------------------------------------------- /Java/test/designpatterns/DecoratorTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import org.junit.Test; 9 | import static org.junit.Assert.*; 10 | /** 11 | * 12 | * @author jtherrell 13 | */ 14 | public class DecoratorTest { 15 | 16 | /** 17 | * Test of getInstance method, of class Singleton. 18 | */ @Test 19 | public void testDecorator() { 20 | Log log = new Log(); 21 | BorderDecorator decorator = new BorderDecorator(new ScrollDecorator(new TextView())); 22 | decorator.draw(log); 23 | String expResult = "textscrollerborder"; 24 | String result = log.toString(); 25 | assertEquals(expResult, result); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /C++/old-Singleton/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Singleton.h" 3 | using namespace std; 4 | 5 | int main (int argc, char * const argv[]) { 6 | Singleton* var1 = Singleton::getInstance(); 7 | Singleton* var2 = Singleton::getInstance(); 8 | cout << "var1 and var2 both refer to one single instance of the Singleton class" << endl; 9 | var1->addToFoo(1); 10 | cout << "var1 added 1 to foo..." << endl; 11 | cout << "var1->getFoo() = " << var1->getFoo() << endl; 12 | cout << "var2->getFoo() = " << var2->getFoo() << endl << endl; 13 | var2->addToFoo(10); 14 | cout << "var2 added 10 to foo..." << endl; 15 | cout << "var1->getFoo() = " << var1->getFoo() << endl; 16 | cout << "var2->getFoo() = " << var2->getFoo() << endl; 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /Java/src/designpatterns/Flyweight.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import java.awt.Font; 9 | /** 10 | * 11 | * @author jtherrell 12 | */ 13 | class Char { 14 | private char c; 15 | public Char(char c) { 16 | this.c = c; 17 | } 18 | public void draw(Font font, Log log) { 19 | log.append(c + ":" + font.getFontName() + "\n"); 20 | } 21 | } 22 | 23 | class CharacterFactory { 24 | private static final int NCHARCODES = 128; 25 | private static Char[] characters = new Char[NCHARCODES]; 26 | 27 | static Char CreateCharacter(char c) { 28 | if (characters[c] == null) 29 | characters[c] = new Char(c); 30 | return characters[c]; 31 | } 32 | } 33 | 34 | 35 | -------------------------------------------------------------------------------- /Java/src/designpatterns/Iterator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import java.util.List; 9 | 10 | /** 11 | * 12 | * @author jtherrell 13 | */ 14 | class Iterator { 15 | private List list; 16 | private int currentIndex; 17 | 18 | public Iterator(List list) { 19 | this.list = list; 20 | currentIndex = 0; 21 | } 22 | 23 | public boolean isEmpty() { 24 | return list.isEmpty(); 25 | } 26 | 27 | public boolean hasNext() { 28 | return currentIndex < list.size(); 29 | } 30 | 31 | public boolean hasPrev() { 32 | return currentIndex > 0; 33 | } 34 | 35 | public T next() { 36 | return list.get(currentIndex++); 37 | } 38 | 39 | public T prev() { 40 | return list.get(--currentIndex); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Java/src/designpatterns/Prototype.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | /** 9 | * 10 | * @author jtherrell 11 | */ 12 | class House implements Cloneable { 13 | private int numOfDoors; 14 | private int numOfWindows; 15 | private int numOfStories; 16 | 17 | public House(int doorsNum, int windowsNum, int storiesNum) { 18 | numOfDoors = doorsNum; 19 | numOfWindows = windowsNum; 20 | numOfStories = storiesNum; 21 | } 22 | public void numOfDoors(int num) { 23 | numOfDoors = num; 24 | } 25 | public void numOfWindows(int num) { 26 | numOfWindows = num; 27 | } 28 | public void numOfStories(int num) { 29 | numOfStories = num; 30 | } 31 | 32 | @Override 33 | protected House clone() { 34 | return new House(numOfDoors, numOfWindows, numOfStories); 35 | } 36 | } -------------------------------------------------------------------------------- /Java/test/designpatterns/SingletonTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import org.junit.Test; 9 | import static org.junit.Assert.*; 10 | 11 | /** 12 | * 13 | * @author jtherrell 14 | */ 15 | public class SingletonTest { 16 | 17 | /** 18 | * Test of getInstance method, of class Singleton. 19 | */ @Test 20 | public void testGetInstance() { 21 | Singleton expResult = Singleton.getInstance(); 22 | Singleton result = Singleton.getInstance(); 23 | assertEquals(expResult, result); 24 | } 25 | 26 | /** 27 | * Test of addToFoo method, of class Singleton. 28 | */ @Test 29 | public void testAddToFoo() { 30 | int num = 10; 31 | Singleton instance = Singleton.getInstance(); 32 | int expResult = instance.getFoo() + num; 33 | instance.addToFoo(num); 34 | int result = instance.getFoo(); 35 | assertEquals(expResult, result); 36 | } 37 | } -------------------------------------------------------------------------------- /Java/test/designpatterns/ProxyTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import org.junit.Test; 9 | import static org.junit.Assert.*; 10 | /** 11 | * 12 | * @author jtherrell 13 | */ 14 | public class ProxyTest { 15 | 16 | /** 17 | * Test of getInstance method, of class Singleton. 18 | */ @Test 19 | public void testProxyLazyLoad() { 20 | ImageProxy proxy = new ImageProxy("example.jpg"); 21 | boolean expResult = false; 22 | boolean result = proxy.isImageLoaded(); 23 | assertEquals(expResult, result); 24 | } 25 | 26 | /** 27 | * Test of getInstance method, of class Singleton. 28 | */ @Test 29 | public void testProxyLoadOnDraw() { 30 | ImageProxy proxy = new ImageProxy("example.jpg"); 31 | proxy.draw(); 32 | boolean expResult = true; 33 | boolean result = proxy.isImageLoaded(); 34 | assertEquals(expResult, result); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Java/test/designpatterns/AbstractFactoryTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import org.junit.Test; 9 | import static org.junit.Assert.*; 10 | /** 11 | * 12 | * @author jtherrell 13 | */ 14 | public class AbstractFactoryTest { 15 | 16 | /** 17 | * Test of Adapter class' adherence to the GUIComponent interface. 18 | */ @Test 19 | public void testAbstractFactory() { 20 | MazeFactory factory = BombedMazeFactory.GetInstance(); 21 | Maze myMaze = factory.makeMaze(); 22 | Wall rm1_wall = factory.makeWall(); 23 | Room rm1 = factory.makeRoom(1); 24 | Room rm2 = factory.makeRoom(2); 25 | Door myDoor = factory.makeDoor(rm1, rm2); 26 | assertEquals(BombedDoor.class, myDoor.getClass()); 27 | assertEquals(BombedWall.class, rm1_wall.getClass()); 28 | assertEquals(BombedRoom.class, rm1.getClass()); 29 | assertEquals(BombedMaze.class, myMaze.getClass()); 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Java/test/designpatterns/InterpreterTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import org.junit.Test; 9 | import static org.junit.Assert.*; 10 | 11 | /** 12 | * 13 | * @author jtherrell 14 | */ 15 | public class InterpreterTest { 16 | 17 | public InterpreterTest() { 18 | } 19 | 20 | // TODO add test methods here. 21 | // The methods must be annotated with annotation @Test. For example: 22 | // 23 | @Test 24 | public void hello() { 25 | BooleanExp expression; 26 | Context context = new Context(); 27 | 28 | VariableExp x = new VariableExp("X"); 29 | VariableExp y = new VariableExp("Y"); 30 | 31 | expression = new OrExp( 32 | new AndExp(new Constant(true), x), 33 | new AndExp(y, new NotExp(x))); 34 | 35 | context.assign(x, false); 36 | context.assign(y, true); 37 | 38 | boolean result = expression.evaluate(context); 39 | assertTrue(result); 40 | } 41 | 42 | } -------------------------------------------------------------------------------- /Java/test/designpatterns/BridgeTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import org.junit.Test; 9 | import static org.junit.Assert.*; 10 | 11 | /** 12 | * 13 | * @author jtherrell 14 | */ 15 | public class BridgeTest { 16 | 17 | /** 18 | * Test of draw method, of class IconWindow. 19 | */ @Test 20 | public void testIconWindowDraw() { 21 | Log log = new Log(); 22 | IconWindow icon = new IconWindow(log); 23 | icon.draw(); 24 | String expResult = "hellohellohellohelloworld"; 25 | String result = log.toString(); 26 | assertEquals(expResult, result); 27 | } 28 | 29 | /** 30 | * Test of draw method, of class TransientWindow. 31 | */ @Test 32 | public void testTransientWindowDraw() { 33 | Log log = new Log(); 34 | TransientWindow transWin = new TransientWindow(log); 35 | transWin.draw(); 36 | String expResult = "wowwowwowwow"; 37 | String result = log.toString(); 38 | assertEquals(expResult, result); 39 | } 40 | 41 | } -------------------------------------------------------------------------------- /Java/test/designpatterns/CommandTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import org.junit.Test; 9 | import static org.junit.Assert.*; 10 | /** 11 | * 12 | * @author jtherrell 13 | */ 14 | public class CommandTest { 15 | /** 16 | * Test of getInstance method, of class Singleton. 17 | */ @Test 18 | public void testCommand() { 19 | Log log = new Log(); 20 | Application app = new Application(log); 21 | Menu appMenu = new Menu(); 22 | MenuItem open = new MenuItem("Open", new OpenCommand(app)); 23 | MenuItem paste = new MenuItem("Paste", new PasteCommand(app)); 24 | appMenu.addMenuItem(open); 25 | appMenu.addMenuItem(paste); 26 | 27 | // Now we'll simulate the clicking of both MenuItems... 28 | open.clicked(); 29 | paste.clicked(); 30 | 31 | String expResult = "./untitled.txt opened...Paste to ./untitled.txt"; 32 | String result = log.toString(); 33 | System.out.print(result); 34 | 35 | assertEquals(expResult, result); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Java/src/designpatterns/Adapter.java: -------------------------------------------------------------------------------- 1 | package designpatterns; 2 | import java.awt.Rectangle; 3 | import java.awt.Point; 4 | import java.awt.Dimension; 5 | 6 | interface GUIComponent { 7 | public Rectangle boundingBox(); 8 | } 9 | 10 | class TextShapeAdapter implements GUIComponent 11 | { 12 | private TextBox text; 13 | 14 | public TextShapeAdapter() { 15 | text = new TextBox(); 16 | } 17 | 18 | public Rectangle boundingBox() { 19 | return new Rectangle(text.getOrigin(), text.getExtent()); 20 | } 21 | } 22 | 23 | class Shape implements GUIComponent 24 | { 25 | private Rectangle boundingBox; 26 | 27 | public Shape() { 28 | boundingBox = new Rectangle(0,0,100,100); 29 | } 30 | public Rectangle boundingBox() { 31 | return boundingBox; 32 | } 33 | } 34 | 35 | class TextBox 36 | { 37 | private Point origin; 38 | private Dimension dimension; 39 | 40 | public TextBox() { 41 | origin = new Point(0,0); 42 | dimension = new Dimension(10,10); 43 | } 44 | 45 | public Point getOrigin() { 46 | return origin; 47 | } 48 | 49 | public Dimension getExtent() { 50 | return dimension; 51 | } 52 | } -------------------------------------------------------------------------------- /Java/test/designpatterns/BuilderTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import org.junit.Test; 9 | import static org.junit.Assert.*; 10 | 11 | /** 12 | * 13 | * @author jtherrell 14 | */ 15 | public class BuilderTest { 16 | 17 | @Test 18 | public void testSomeMethod() { 19 | String testString = "hello world!"; 20 | ConcreteBuilderA builder = new ConcreteBuilderA(); 21 | Director director = new Director(builder); 22 | director.convert(testString); 23 | BuildProduct finalProduct = builder.getProduct(); 24 | 25 | String expResult = "HELLO WORLD!"; 26 | assertEquals(expResult, finalProduct.toString()); 27 | } 28 | 29 | @Test 30 | public void testSomeMethod2() { 31 | String testString = "hello world!"; 32 | ConcreteBuilderB builder = new ConcreteBuilderB(); 33 | Director director = new Director(builder); 34 | director.convert(testString); 35 | BuildProduct finalProduct = builder.getProduct(); 36 | 37 | String expResult = "HeLlO WoRlD!"; 38 | assertEquals(expResult, finalProduct.toString()); 39 | } 40 | 41 | } -------------------------------------------------------------------------------- /Java/src/designpatterns/Strategy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | /** 9 | * 10 | * @author jtherrell 11 | */ 12 | class Composition { 13 | private Compositor compositor; 14 | 15 | public Composition(Compositor compositor) { 16 | this.compositor = compositor; 17 | } 18 | 19 | public void repair(Log log) { 20 | compositor.compose(log); 21 | } 22 | 23 | } 24 | 25 | abstract class Compositor { 26 | abstract public void compose (Log log); 27 | } 28 | 29 | class SimpleCompositor extends Compositor { 30 | 31 | @Override 32 | public void compose(Log log) { 33 | log.append("Performing SimpleCompositor algorithm..."); 34 | } 35 | } 36 | 37 | class TeXCompositor extends Compositor { 38 | public TeXCompositor() { 39 | 40 | } 41 | 42 | @Override 43 | public void compose(Log log) { 44 | log.append("Performing TeXCompositor algorithm..."); 45 | } 46 | } 47 | 48 | class ArrayCompositor extends Compositor { 49 | public ArrayCompositor() { 50 | 51 | } 52 | 53 | @Override 54 | public void compose(Log log) { 55 | log.append("Performing ArrayCompositor algorithm..."); 56 | } 57 | } -------------------------------------------------------------------------------- /Java/test/designpatterns/TemplateMethodTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import org.junit.AfterClass; 9 | import org.junit.BeforeClass; 10 | import org.junit.Test; 11 | import static org.junit.Assert.*; 12 | 13 | /** 14 | * 15 | * @author jtherrell 16 | */ 17 | public class TemplateMethodTest { 18 | 19 | public TemplateMethodTest() { 20 | } 21 | 22 | @BeforeClass 23 | public static void setUpClass() throws Exception { 24 | } 25 | 26 | @AfterClass 27 | public static void tearDownClass() throws Exception { 28 | } 29 | 30 | // TODO add test methods here. 31 | // The methods must be annotated with annotation @Test. For example: 32 | // 33 | @Test 34 | public void testTemplateMethod() { 35 | Log log = new Log(); 36 | UnixWordProcessorApplication app = new UnixWordProcessorApplication(log); 37 | app.openDocument("helloworld.txt"); 38 | String expResult = "TEMPLATE METHOD START:UNIX canOpen:UNIX " 39 | + "doCreate:UNIX aboutTo:TEMPLATE METHOD END"; 40 | String result = log.toString(); 41 | System.out.print(result); 42 | assertEquals(expResult, result); 43 | } 44 | 45 | } -------------------------------------------------------------------------------- /Java/test/designpatterns/ObserverTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import org.junit.Test; 9 | import static org.junit.Assert.*; 10 | 11 | /** 12 | * 13 | * @author jtherrell 14 | */ 15 | public class ObserverTest { 16 | 17 | public ObserverTest() { 18 | } 19 | 20 | // TODO add test methods here. 21 | // The methods must be annotated with annotation @Test. For example: 22 | // 23 | @Test 24 | public void hello() { 25 | Log log = new Log(); 26 | Subject subject = new Subject("Original Title", log); 27 | ObserverA obA = new ObserverA(subject); 28 | ObserverB obB = new ObserverB(subject); 29 | ObserverC obC = new ObserverC(subject); 30 | subject.attach(obA); 31 | subject.attach(obB); 32 | subject.attach(obC); 33 | subject.setTitle("Update Title"); 34 | String expResult = "notifying ObserverA" + "\n" 35 | + "ObserverA notified!" + "\n" 36 | + "notifying ObserverB" + "\n" 37 | + "ObserverB notified!" + "\n" 38 | + "notifying ObserverC" + "\n" 39 | + "ObserverC notified!" + "\n"; 40 | String result = log.toString(); 41 | assertEquals(expResult, result); 42 | } 43 | 44 | } -------------------------------------------------------------------------------- /Java/src/designpatterns/Proxy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | import java.awt.Rectangle; 8 | /** 9 | * 10 | * @author jtherrell 11 | */ 12 | abstract class VisualObject { 13 | protected Rectangle extent; 14 | 15 | abstract public void draw(); 16 | abstract public Rectangle getExtent(); 17 | } 18 | 19 | class ImageProxy extends VisualObject { 20 | private Image image; 21 | private String filename; 22 | 23 | public ImageProxy(String filename) { 24 | this.filename = filename; 25 | extent = null; 26 | } 27 | public void draw(){ 28 | getImage().draw(); 29 | } 30 | public Rectangle getExtent() { 31 | if (extent == null) 32 | return getImage().getExtent(); 33 | return extent; 34 | } 35 | 36 | public boolean isImageLoaded() { 37 | return image != null; 38 | } 39 | 40 | private Image getImage() { 41 | image = new Image(filename); 42 | return image; 43 | } 44 | } 45 | 46 | class Image extends VisualObject { 47 | public Image(String filename) { 48 | // Load the file here using the filename 49 | // get the extent of the loaded image and update extent 50 | extent = new Rectangle(0,0,100,100); 51 | } 52 | public void draw(){} 53 | public Rectangle getExtent(){ return extent; } 54 | } -------------------------------------------------------------------------------- /Java/test/designpatterns/MediatorTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import org.junit.AfterClass; 9 | import org.junit.BeforeClass; 10 | import org.junit.Test; 11 | import static org.junit.Assert.*; 12 | 13 | /** 14 | * 15 | * @author jtherrell 16 | */ 17 | public class MediatorTest { 18 | 19 | public MediatorTest() { 20 | } 21 | 22 | @BeforeClass 23 | public static void setUpClass() throws Exception { 24 | } 25 | 26 | @AfterClass 27 | public static void tearDownClass() throws Exception { 28 | } 29 | 30 | // TODO add test methods here. 31 | // The methods must be annotated with annotation @Test. For example: 32 | // 33 | @Test 34 | public void testMediator() { 35 | Log log = new Log(); 36 | FontDialogMediator mediator = new FontDialogMediator(log); 37 | Widget[] widgets = mediator.getWidgets(); 38 | //Simulate mouse events triggering action on a few widgets 39 | for(int i = 0; i < widgets.length; i++) { 40 | widgets[i].handleMouse(new MouseEvent()); 41 | } 42 | String expResult = "Button changed OK Button changed CANCEL ListBox " + 43 | "changed updating fontName field EntryField changed "; 44 | String result = log.toString(); 45 | assertEquals(expResult, result); 46 | } 47 | 48 | } -------------------------------------------------------------------------------- /Java/src/designpatterns/Decorator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | /** 9 | * 10 | * @author jtherrell 11 | */ 12 | abstract class VisualComponent { 13 | abstract public void draw(Log log); 14 | } 15 | 16 | class TextView extends VisualComponent { 17 | public void draw(Log log){log.append("text");} 18 | } 19 | 20 | abstract class Decorator extends VisualComponent { 21 | private VisualComponent component; 22 | 23 | public Decorator(VisualComponent component) { 24 | this.component = component; 25 | } 26 | 27 | public void draw(Log log) { 28 | component.draw(log); 29 | } 30 | } 31 | 32 | class ScrollDecorator extends Decorator { 33 | 34 | public ScrollDecorator(VisualComponent component) { 35 | super(component); 36 | } 37 | 38 | @Override 39 | public void draw(Log log) { 40 | super.draw(log); 41 | drawScroller(log); 42 | } 43 | 44 | private void drawScroller(Log log) {log.append("scroller");} 45 | } 46 | 47 | class BorderDecorator extends Decorator { 48 | 49 | public BorderDecorator(VisualComponent component) { 50 | super(component); 51 | } 52 | 53 | @Override 54 | public void draw(Log log) { 55 | super.draw(log); 56 | drawBorder(log); 57 | } 58 | 59 | private void drawBorder(Log log) {log.append("border");} 60 | } 61 | 62 | 63 | -------------------------------------------------------------------------------- /Java/test/designpatterns/StateTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import org.junit.Test; 9 | import static org.junit.Assert.*; 10 | 11 | /** 12 | * 13 | * @author jtherrell 14 | */ 15 | public class StateTest { 16 | private TCPConnection connection; 17 | 18 | public StateTest() { 19 | connection = new TCPConnection(); 20 | } 21 | 22 | // TODO add test methods here. 23 | // The methods must be annotated with annotation @Test. For example: 24 | // 25 | @Test 26 | public void hello() { 27 | assertEquals(TCPClosed.class, connection.state().getClass()); 28 | } 29 | 30 | @Test 31 | public void testActiveOpen() { 32 | connection.activeOpen(); 33 | assertEquals(TCPEstablished.class, connection.state().getClass()); 34 | } 35 | 36 | @Test 37 | public void testPassiveOpen() { 38 | connection.passiveOpen(); 39 | assertEquals(TCPListen.class, connection.state().getClass()); 40 | } 41 | 42 | @Test 43 | public void testClose() { 44 | connection.activeOpen(); 45 | connection.close(); 46 | assertEquals(TCPListen.class, connection.state().getClass()); 47 | } 48 | 49 | @Test 50 | public void testSend() { 51 | connection.passiveOpen(); 52 | connection.send(); 53 | assertEquals(TCPEstablished.class, connection.state().getClass()); 54 | } 55 | 56 | } -------------------------------------------------------------------------------- /Java/test/designpatterns/FlyweightTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import org.junit.Test; 9 | import static org.junit.Assert.*; 10 | import java.awt.Font; 11 | /** 12 | * 13 | * @author jtherrell 14 | */ 15 | public class FlyweightTest { 16 | 17 | private static final char[] chars = {'a','b','c','d','e','f'}; 18 | private static final Font[] fonts = {new Font("Arial", Font.BOLD, 12), new Font("Times", Font.ITALIC, 18)}; 19 | /** 20 | * Test of getInstance method, of class Singleton. 21 | */ @Test 22 | public void testFlyweightSingletonBehavior() { 23 | Char[] characters = new Char[chars.length]; 24 | for (int i = 0; i < chars.length; i++) { 25 | characters[i] = CharacterFactory.CreateCharacter(chars[i]); 26 | assertEquals(characters[i], CharacterFactory.CreateCharacter(chars[i])); 27 | } 28 | } 29 | 30 | /** 31 | * Test of getInstance method, of class Singleton. 32 | */ @Test 33 | public void testFlyweightDraw() { 34 | Log log = new Log(); 35 | Char[] characters = new Char[chars.length]; 36 | for (int i = 0; i < chars.length; i++) { 37 | CharacterFactory.CreateCharacter(chars[i]).draw(fonts[i%2], log); 38 | } 39 | String expResult = "a:Arial-BoldMT\nb:Times-Italic\nc:Arial-BoldMT\n" 40 | + "d:Times-Italic\ne:Arial-BoldMT\nf:Times-Italic\n"; 41 | String result = log.toString(); 42 | assertEquals(expResult, result); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /Java/test/designpatterns/StrategyTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import org.junit.Test; 9 | import static org.junit.Assert.*; 10 | 11 | /** 12 | * 13 | * @author jtherrell 14 | */ 15 | public class StrategyTest { 16 | private Log log; 17 | 18 | public StrategyTest() { 19 | log = new Log(); 20 | } 21 | 22 | // TODO add test methods here. 23 | // The methods must be annotated with annotation @Test. For example: 24 | // 25 | @Test 26 | public void testSimpleCompositor() { 27 | Composition composition = new Composition(new SimpleCompositor()); 28 | composition.repair(log); 29 | String expResult = "Performing SimpleCompositor algorithm..."; 30 | String result = log.toString(); 31 | assertEquals(expResult, result); 32 | } 33 | 34 | @Test 35 | public void testTeXCompositor() { 36 | Composition composition = new Composition(new TeXCompositor()); 37 | composition.repair(log); 38 | String expResult = "Performing TeXCompositor algorithm..."; 39 | String result = log.toString(); 40 | assertEquals(expResult, result); 41 | } 42 | 43 | @Test 44 | public void testArrayCompositor() { 45 | Composition composition = new Composition(new ArrayCompositor()); 46 | composition.repair(log); 47 | String expResult = "Performing ArrayCompositor algorithm..."; 48 | String result = log.toString(); 49 | assertEquals(expResult, result); 50 | } 51 | 52 | } -------------------------------------------------------------------------------- /Java/test/designpatterns/VisitorTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import java.util.List; 9 | import java.util.ArrayList; 10 | import org.junit.Test; 11 | import static org.junit.Assert.*; 12 | 13 | /** 14 | * 15 | * @author jtherrell 16 | */ 17 | public class VisitorTest { 18 | private List parts; 19 | private Equipment chassis; 20 | 21 | public VisitorTest() { 22 | parts = new ArrayList(); 23 | parts.add(new FloppyDisk("iFloppy", 10)); 24 | parts.add(new FloppyDisk("MyFloppy", 5)); 25 | parts.add(new Card("iCard", 100)); 26 | parts.add(new Card("MyCard", 50)); 27 | chassis = new Chassis("Chassis", 1000, parts); 28 | } 29 | 30 | // TODO add test methods here. 31 | // The methods must be annotated with annotation @Test. For example: 32 | // 33 | @Test 34 | public void testInventoryVisitor() { 35 | List inventory = new ArrayList(); 36 | InventoryVisitor visitor = new InventoryVisitor(inventory); 37 | chassis.accept(visitor); 38 | 39 | int expResult = 5; 40 | int result = inventory.size(); 41 | assertEquals(expResult, result); 42 | } 43 | 44 | @Test 45 | public void testPriceVisitor() { 46 | PricingVisitor priceVisitor = new PricingVisitor(); 47 | chassis.accept(priceVisitor); 48 | double expResult = 1165; 49 | double result = priceVisitor.total(); 50 | assertEquals(expResult, result, 0); 51 | } 52 | 53 | } -------------------------------------------------------------------------------- /Java/src/designpatterns/Memento.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import java.awt.Point; 9 | import java.util.Stack; 10 | 11 | /** 12 | * 13 | * @author jtherrell 14 | */ 15 | class Graphix { 16 | private Point position; 17 | 18 | public Graphix(Point position) { 19 | this.position = position; 20 | } 21 | 22 | public void move(Point delta) { 23 | position.x += delta.x; 24 | position.y += delta.y; 25 | } 26 | 27 | public GraphixMemento createMemento() { 28 | return new GraphixMemento(new Point(position.x, position.y)); 29 | } 30 | 31 | public void setMemento(GraphixMemento memento) { 32 | position = memento.state(); 33 | } 34 | 35 | public Point position() { 36 | return position; 37 | } 38 | } 39 | 40 | class GraphixMemento{ 41 | private Point position; 42 | 43 | public GraphixMemento(Point position) { 44 | this.position = position; 45 | } 46 | 47 | public Point state() { 48 | return position; 49 | } 50 | } 51 | 52 | class MoveCommand { 53 | private Graphix target; 54 | private Stack state; 55 | 56 | public MoveCommand (Graphix target) { 57 | this.target = target; 58 | state = new Stack(); 59 | } 60 | 61 | public void execute(Point delta) { 62 | 63 | state.push(target.createMemento()); 64 | target.move(delta); 65 | } 66 | 67 | public void unexecute() { 68 | if(!state.empty()) 69 | target.setMemento(state.pop()); 70 | } 71 | } 72 | 73 | 74 | -------------------------------------------------------------------------------- /Java/src/designpatterns/AbstractFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | /** 9 | * 10 | * @author jtherrell 11 | */ 12 | abstract class MazeFactory { 13 | abstract public Maze makeMaze(); 14 | abstract public Wall makeWall(); 15 | abstract public Room makeRoom(int n); 16 | abstract public Door makeDoor(Room r1, Room r2); 17 | } 18 | 19 | class BombedMazeFactory extends MazeFactory { 20 | private static BombedMazeFactory s_instance; 21 | 22 | public Maze makeMaze() 23 | { return new BombedMaze(); } 24 | public Wall makeWall() 25 | { return new BombedWall(); } 26 | public Room makeRoom(int n) 27 | { return new BombedRoom(n); } 28 | public Door makeDoor(Room r1, Room r2) 29 | { return new BombedDoor(r1, r2); } 30 | public static BombedMazeFactory GetInstance() { 31 | if (s_instance == null) 32 | s_instance = new BombedMazeFactory(); 33 | return s_instance; 34 | } 35 | } 36 | 37 | abstract class Maze {} 38 | class BombedMaze extends Maze{} 39 | 40 | class Wall {} 41 | class BombedWall extends Wall{} 42 | 43 | class Room { 44 | int roomNumber; 45 | public Room(int n) { 46 | roomNumber = n; 47 | } 48 | } 49 | class BombedRoom extends Room { 50 | public BombedRoom(int n) { 51 | super(n); 52 | } 53 | } 54 | 55 | class Door { 56 | Room r1, r2; 57 | public Door(Room r1, Room r2) { 58 | this.r1 = r1; 59 | this.r2 = r2; 60 | } 61 | } 62 | 63 | class BombedDoor extends Door { 64 | public BombedDoor(Room r1, Room r2) { 65 | super(r1, r2); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /Java/src/designpatterns/TemplateMethod.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import java.util.ArrayList; 9 | 10 | /** 11 | * 12 | * @author jtherrell 13 | */ 14 | abstract class WordProcessorApplication { 15 | private ArrayList docs; 16 | protected Log log; 17 | 18 | public WordProcessorApplication(Log log) { 19 | docs = new ArrayList(); 20 | this.log = log; 21 | } 22 | 23 | public void openDocument(String filename) { 24 | log.append("TEMPLATE METHOD START:"); 25 | if (!canOpenDocument(filename)) 26 | return; 27 | Document doc = doCreateDocument(filename); 28 | if (doc != null) { 29 | docs.add(doc); 30 | aboutToOpenDocument(); 31 | doc.open(); 32 | doc.read(); 33 | } 34 | log.append("TEMPLATE METHOD END"); 35 | } 36 | abstract public boolean canOpenDocument(String filename); 37 | abstract public Document doCreateDocument(String filename); 38 | abstract public void aboutToOpenDocument(); 39 | } 40 | 41 | class UnixWordProcessorApplication extends WordProcessorApplication { 42 | 43 | public UnixWordProcessorApplication(Log log) { 44 | super(log); 45 | } 46 | 47 | @Override 48 | public boolean canOpenDocument(String filename) { 49 | log.append("UNIX canOpen:"); 50 | return true; 51 | } 52 | 53 | @Override 54 | public Document doCreateDocument(String filename) { 55 | log.append("UNIX doCreate:"); 56 | return new Document(filename); 57 | } 58 | 59 | @Override 60 | public void aboutToOpenDocument() { 61 | log.append("UNIX aboutTo:"); 62 | // Do any setup prior to opening doc 63 | } 64 | } -------------------------------------------------------------------------------- /Java/src/designpatterns/Builder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | /** 8 | * 9 | * @author jtherrell 10 | */ 11 | 12 | class Director { 13 | private Builder builder; 14 | public Director(Builder b) { 15 | builder = b; 16 | } 17 | public void convert(String string) { 18 | for (int i = 0; i < string.length(); i++) { 19 | if (i % 2 == 0) 20 | builder.buildPartA(string.charAt(i)); 21 | else 22 | builder.buildPartB(string.charAt(i)); 23 | } 24 | } 25 | } 26 | 27 | abstract class Builder { 28 | protected BuildProduct product; 29 | abstract public void buildPartA(char c); 30 | abstract public void buildPartB(char c); 31 | } 32 | 33 | class ConcreteBuilderA extends Builder { 34 | public ConcreteBuilderA() { 35 | product = new BuildProduct(); 36 | } 37 | public void buildPartA(char c) { 38 | buildPartB(c); 39 | } 40 | public void buildPartB(char c) { 41 | product.append(Character.toUpperCase(c)); 42 | } 43 | public BuildProduct getProduct() { 44 | return product; 45 | } 46 | } 47 | 48 | class ConcreteBuilderB extends Builder { 49 | public ConcreteBuilderB() { 50 | product = new BuildProduct(); 51 | } 52 | public void buildPartA(char c) { 53 | product.append(Character.toUpperCase(c)); 54 | } 55 | public void buildPartB(char c) { 56 | product.append(c); 57 | } 58 | public BuildProduct getProduct() { 59 | return product; 60 | } 61 | } 62 | 63 | class BuildProduct { 64 | private Log doc; 65 | 66 | public BuildProduct() { 67 | doc = new Log(); 68 | } 69 | 70 | public void append(char c) { 71 | doc.append(c); 72 | } 73 | 74 | @Override 75 | public String toString() { 76 | return doc.toString(); 77 | } 78 | } -------------------------------------------------------------------------------- /Java/test/designpatterns/ChainOfResponsibilityTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import org.junit.Test; 9 | import static org.junit.Assert.*; 10 | 11 | /** 12 | * 13 | * @author jtherrell 14 | */ 15 | public class ChainOfResponsibilityTest { 16 | final int PRINT_TOPIC = 1; 17 | final int PAPER_ORIENTATION_TOPIC = 2; 18 | final int APPLICATION_TOPIC = 3; 19 | 20 | private HelpApplication application; 21 | private HelpDialog dialog; 22 | private HelpButton button; 23 | 24 | private Log log; 25 | 26 | public ChainOfResponsibilityTest() { 27 | log = new Log(); 28 | HelpHandler.log = log; 29 | application = new HelpApplication(APPLICATION_TOPIC); 30 | dialog = new HelpDialog(application, PRINT_TOPIC); 31 | button = new HelpButton(dialog, PAPER_ORIENTATION_TOPIC); 32 | } 33 | 34 | // TODO add test methods here. 35 | // The methods must be annotated with annotation @Test. For example: 36 | // 37 | @Test 38 | public void testExpectedButtonHandle() { 39 | button.handleHelp(PAPER_ORIENTATION_TOPIC); 40 | String expResult = "In HelpButton...Button helped!"; 41 | String result = log.toString(); 42 | assertEquals(expResult, result); 43 | } 44 | 45 | @Test 46 | public void testExpectedDialogHandle() { 47 | button.handleHelp(PRINT_TOPIC); 48 | String expResult = "In HelpButton...In HelpHandler..." + 49 | "In HelpDialog...Dialog helped!"; 50 | String result = log.toString(); 51 | assertEquals(expResult, result); 52 | } 53 | 54 | @Test 55 | public void testExpectedApplicationHandle() { 56 | button.handleHelp(APPLICATION_TOPIC); 57 | String expResult = "In HelpButton...In HelpHandler..." + 58 | "In HelpDialog...In HelpHandler..." + 59 | "In HelpApplication...Application helped!"; 60 | String result = log.toString(); 61 | assertEquals(expResult, result); 62 | } 63 | } -------------------------------------------------------------------------------- /Java/src/designpatterns/Composite.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import java.util.ArrayList; 9 | 10 | /** 11 | * 12 | * @author jtherrell 13 | */ 14 | abstract class Graphic { 15 | abstract public void draw(Log log); 16 | abstract public boolean add(Graphic g); 17 | abstract public boolean remove(Graphic g); 18 | abstract public Graphic getChild(int index); 19 | } 20 | 21 | class Picture extends Graphic { 22 | private ArrayList children; 23 | 24 | public Picture() { 25 | children = new ArrayList(); 26 | } 27 | 28 | public void draw(Log log) { 29 | for (int i = 0; i < children.size(); i++) 30 | children.get(i).draw(log); 31 | } 32 | public boolean add(Graphic g) { 33 | children.add(g); 34 | return children.contains(g); 35 | } 36 | public boolean remove(Graphic g) { 37 | children.remove(g); 38 | return !children.contains(g); 39 | } 40 | public Graphic getChild(int index) { 41 | return index < children.size() ? children.get(index) : null; 42 | } 43 | } 44 | 45 | class Line extends Graphic { 46 | public void draw(Log log) {log.append("Line");} 47 | public boolean add(Graphic g) { return false; } // do nothing 48 | public boolean remove(Graphic g) { return false; } // do nothing 49 | public Graphic getChild(int index) {return null;} 50 | } 51 | 52 | class Rectangle extends Graphic { 53 | public void draw(Log log) {log.append("Rect");} 54 | public boolean add(Graphic g) { return false; } // do nothing 55 | public boolean remove(Graphic g) { return false; } // do nothing 56 | public Graphic getChild(int index) {return null;} 57 | } 58 | 59 | class Text extends Graphic { 60 | public void draw(Log log) {log.append("Text");} 61 | public boolean add(Graphic g) { return false; } // do nothing 62 | public boolean remove(Graphic g) { return false; } // do nothing 63 | public Graphic getChild(int index) {return null;} 64 | } -------------------------------------------------------------------------------- /Java/test/designpatterns/MementoTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import java.awt.Point; 9 | import org.junit.Test; 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * 14 | * @author jtherrell 15 | */ 16 | public class MementoTest { 17 | 18 | public MementoTest() { 19 | } 20 | 21 | // TODO add test methods here. 22 | // The methods must be annotated with annotation @Test. For example: 23 | // 24 | @Test 25 | public void testMoveExecuteOnce() { 26 | Point delta = new Point(5,5); 27 | Graphix g = new Graphix(new Point(100,100)); 28 | MoveCommand move = new MoveCommand(g); 29 | move.execute(delta); 30 | 31 | Point expResult = new Point(105,105); 32 | Point result = g.position(); 33 | assertEquals(expResult, result); 34 | } 35 | 36 | @Test 37 | public void testMoveExecuteMany() { 38 | Point delta = new Point(5,5); 39 | Graphix g = new Graphix(new Point(100,100)); 40 | MoveCommand move = new MoveCommand(g); 41 | for(int i = 0; i < 10; i++) 42 | move.execute(delta); 43 | 44 | Point expResult = new Point(150,150); 45 | Point result = g.position(); 46 | assertEquals(expResult, result); 47 | } 48 | 49 | @Test 50 | public void testMoveUndoOnce() { 51 | Point delta = new Point(5,5); 52 | Graphix g = new Graphix(new Point(100,100)); 53 | MoveCommand move = new MoveCommand(g); 54 | move.execute(delta); 55 | move.unexecute(); 56 | Point expResult = new Point(100,100); 57 | Point result = g.position(); 58 | assertEquals(expResult, result); 59 | } 60 | 61 | @Test 62 | public void testMoveUndoMany() { 63 | Point delta = new Point(5,5); 64 | Graphix g = new Graphix(new Point(100,100)); 65 | MoveCommand move = new MoveCommand(g); 66 | for(int i = 0; i < 10; i++) 67 | move.execute(delta); 68 | for(int i = 0; i < 10; i++) { 69 | move.unexecute(); 70 | } 71 | Point expResult = new Point(100,100); 72 | Point result = g.position(); 73 | assertEquals(expResult, result); 74 | } 75 | 76 | } -------------------------------------------------------------------------------- /C++/abfactory.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | */ 3 | #include "MazeParts.h" 4 | #include "MazeGame.h" 5 | #define MazeFactory_H 6 | /* 7 | */ 8 | class MazeFactory { 9 | public: 10 | MazeFactory(); 11 | /* 12 | */ 13 | virtual Maze* MakeMaze() const 14 | { return new Maze; } 15 | virtual Wall* MakeWall() const 16 | { return new Wall; } 17 | virtual Room* MakeRoom(int n) const 18 | { return new Room(n); } 19 | virtual Door* MakeDoor(Room* r1, Room* r2) const 20 | { return new Door(r1, r2); } 21 | }; 22 | /* 23 | */ 24 | Maze* MazeGame::CreateMaze (MazeFactory& factory) { 25 | Maze* aMaze = factory.MakeMaze(); 26 | Room* r1 = factory.MakeRoom(1); 27 | Room* r2 = factory.MakeRoom(2); 28 | Door* aDoor = factory.MakeDoor(r1, r2); 29 | 30 | aMaze->AddRoom(r1); 31 | aMaze->AddRoom(r2); 32 | /* 33 | */ 34 | r1->SetSide(North, factory.MakeWall()); 35 | r1->SetSide(East, aDoor); 36 | r1->SetSide(South, factory.MakeWall()); 37 | r1->SetSide(West, factory.MakeWall()); 38 | /* 39 | */ 40 | r2->SetSide(North, factory.MakeWall()); 41 | r2->SetSide(East, factory.MakeWall()); 42 | r2->SetSide(South, factory.MakeWall()); 43 | r2->SetSide(West, aDoor); 44 | 45 | return aMaze; 46 | } 47 | /* 48 | */ 49 | class EnchantedMazeFactory : public MazeFactory { 50 | public: 51 | EnchantedMazeFactory(); 52 | /* 53 | */ 54 | virtual Room* MakeRoom(int n) const 55 | { return new EnchantedRoom(n, CastSpell()); } 56 | /* 57 | */ 58 | virtual Door* MakeDoor(Room* r1, Room* r2) const 59 | { return new DoorNeedingSpell(r1, r2); } 60 | /* 61 | */ 62 | protected: 63 | Spell* CastSpell() const; 64 | }; 65 | /* 66 | */ 67 | #define EnchantedMazeFactory_H 68 | #include "MazeFactories.h" 69 | /* 70 | */ 71 | Wall* BombedMazeFactory::MakeWall () const { 72 | return new BombedWall; 73 | } 74 | /* 75 | */ 76 | Room* BombedMazeFactory::MakeRoom(int n) const { 77 | return new RoomWithABomb(n); 78 | } 79 | /* 80 | */ 81 | void dummy() { 82 | /* 83 | */ 84 | MazeGame game; 85 | BombedMazeFactory factory; 86 | 87 | game.CreateMaze(factory); 88 | /* 89 | */ 90 | } 91 | /* 92 | */ 93 | -------------------------------------------------------------------------------- /Java/src/designpatterns/Observer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | /** 12 | * 13 | * @author jtherrell 14 | */ 15 | /* 16 | */ 17 | class Subject { 18 | private List observers; 19 | private Log log; 20 | private String title; 21 | 22 | public Subject(String title, Log log) { 23 | observers = new ArrayList(); 24 | this.title = title; 25 | this.log = log; 26 | } 27 | 28 | public void notifyObservers() { 29 | for (Observer observer : observers) { 30 | log.append("notifying " + observer.getClass().getSimpleName() + "\n"); 31 | observer.update(); 32 | } 33 | } 34 | 35 | public void attach(Observer observer) { 36 | if (observer != null) 37 | observers.add(observer); 38 | } 39 | 40 | public void detach(Observer observer) { 41 | observers.remove(observer); 42 | } 43 | 44 | public Log log() { 45 | return log; 46 | } 47 | 48 | public String title() { 49 | return title; 50 | } 51 | 52 | public void setTitle(String title) { 53 | this.title = title; 54 | notifyObservers(); 55 | } 56 | } 57 | 58 | interface Observer { 59 | public void update(); 60 | } 61 | 62 | class ObserverA implements Observer { 63 | private Subject subject; 64 | 65 | public ObserverA(Subject subject) { 66 | this.subject = subject; 67 | } 68 | 69 | public void update() { 70 | subject.log().append(this.getClass().getSimpleName() + " notified!\n"); 71 | } 72 | } 73 | 74 | class ObserverB implements Observer { 75 | private Subject subject; 76 | 77 | public ObserverB(Subject subject) { 78 | this.subject = subject; 79 | } 80 | 81 | public void update() { 82 | subject.log().append(this.getClass().getSimpleName() + " notified!\n"); 83 | } 84 | } 85 | 86 | class ObserverC implements Observer { 87 | private Subject subject; 88 | 89 | public ObserverC(Subject subject) { 90 | this.subject = subject; 91 | } 92 | 93 | public void update() { 94 | subject.log().append(this.getClass().getSimpleName() + " notified!\n"); 95 | } 96 | } -------------------------------------------------------------------------------- /C++/AbstractFactory/AbstractFactory.cpp: -------------------------------------------------------------------------------- 1 | #include "Shared/MazeParts.h" 2 | #include "Shared/MazeGame.h" 3 | #define MazeFactory_H 4 | /* 5 | */ 6 | class MazeFactory { 7 | public: 8 | MazeFactory(); 9 | /* 10 | */ 11 | virtual Maze* MakeMaze() const 12 | { return new Maze; } 13 | virtual Wall* MakeWall() const 14 | { return new Wall; } 15 | virtual Room* MakeRoom(int n) const 16 | { return new Room(n); } 17 | virtual Door* MakeDoor(Room* r1, Room* r2) const 18 | { return new Door(r1, r2); } 19 | }; 20 | /* 21 | */ 22 | Maze* MazeGame::CreateMaze (MazeFactory& factory) { 23 | Maze* aMaze = factory.MakeMaze(); 24 | Room* r1 = factory.MakeRoom(1); 25 | Room* r2 = factory.MakeRoom(2); 26 | Door* aDoor = factory.MakeDoor(r1, r2); 27 | 28 | aMaze->AddRoom(r1); 29 | aMaze->AddRoom(r2); 30 | /* 31 | */ 32 | r1->SetSide(North, factory.MakeWall()); 33 | r1->SetSide(East, aDoor); 34 | r1->SetSide(South, factory.MakeWall()); 35 | r1->SetSide(West, factory.MakeWall()); 36 | /* 37 | */ 38 | r2->SetSide(North, factory.MakeWall()); 39 | r2->SetSide(East, factory.MakeWall()); 40 | r2->SetSide(South, factory.MakeWall()); 41 | r2->SetSide(West, aDoor); 42 | 43 | return aMaze; 44 | } 45 | /* 46 | */ 47 | class EnchantedMazeFactory : public MazeFactory { 48 | public: 49 | EnchantedMazeFactory(); 50 | /* 51 | */ 52 | virtual Room* MakeRoom(int n) const 53 | { return new EnchantedRoom(n, CastSpell()); } 54 | /* 55 | */ 56 | virtual Door* MakeDoor(Room* r1, Room* r2) const 57 | { return new DoorNeedingSpell(r1, r2); } 58 | /* 59 | */ 60 | protected: 61 | Spell* CastSpell() const; 62 | }; 63 | /* 64 | */ 65 | #define EnchantedMazeFactory_H 66 | #include "C++/MazeFactories.H" 67 | /* 68 | */ 69 | Wall* BombedMazeFactory::MakeWall () const { 70 | return new BombedWall; 71 | } 72 | /* 73 | */ 74 | Room* BombedMazeFactory::MakeRoom(int n) const { 75 | return new RoomWithABomb(n); 76 | } 77 | /* 78 | */ 79 | void dummy() { 80 | /* 81 | */ 82 | MazeGame game; 83 | BombedMazeFactory factory; 84 | 85 | game.CreateMaze(factory); 86 | /* 87 | */ 88 | } 89 | /* 90 | */ 91 | -------------------------------------------------------------------------------- /C++/tmethod.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | */ 3 | #include "Foundation.h" 4 | using namespace std; 5 | /* 6 | */ 7 | class Document; 8 | class Application { 9 | public: 10 | void OpenDocument(const char*); 11 | virtual bool CanOpenDocument(const char*); 12 | virtual Document* DoCreateDocument(); 13 | virtual void AboutToOpenDocument(Document* doc); 14 | private: 15 | List* _docs; 16 | }; 17 | class Document { 18 | public: 19 | virtual void Open(); 20 | virtual void DoRead(); 21 | }; 22 | /* 23 | */ 24 | void Application::OpenDocument (const char* name) { 25 | if (!CanOpenDocument(name)) { 26 | // cannot handle this document 27 | return; 28 | } 29 | /* 30 | */ 31 | Document* doc = DoCreateDocument(); 32 | 33 | if (doc) { 34 | _docs->Append(*doc); 35 | AboutToOpenDocument(doc); 36 | doc->Open(); 37 | doc->DoRead(); 38 | } 39 | } 40 | /* 41 | */ 42 | class ParentClass { 43 | public: 44 | void Operation(); 45 | virtual void HookOperation(); 46 | }; 47 | class DerivedClass : public ParentClass { 48 | public: 49 | void Operation(); 50 | virtual void HookOperation(); 51 | }; 52 | /* 53 | */ 54 | void DerivedClass::Operation () { 55 | // DerivedClass extended behavior 56 | ParentClass::Operation(); 57 | } 58 | /* 59 | */ 60 | void ParentClass::Operation () { 61 | // ParentClass behavior 62 | HookOperation(); 63 | } 64 | /* 65 | */ 66 | void ParentClass::HookOperation () { } 67 | /* 68 | */ 69 | void DerivedClass::HookOperation () { 70 | // derived class extension 71 | } 72 | /* 73 | */ 74 | class View { 75 | public: 76 | void Display(); 77 | void SetFocus(); 78 | virtual void DoDisplay(); 79 | void ResetFocus(); 80 | }; 81 | 82 | class MyView : public View { 83 | public: 84 | virtual void DoDisplay(); 85 | }; 86 | /* 87 | */ 88 | void View::Display () { 89 | SetFocus(); 90 | DoDisplay(); 91 | ResetFocus(); 92 | } 93 | /* 94 | */ 95 | void View::DoDisplay () { } 96 | /* 97 | */ 98 | void MyView::DoDisplay () { 99 | // render the view's contents 100 | } 101 | /* 102 | */ 103 | -------------------------------------------------------------------------------- /Java/src/designpatterns/ChainOfResponsibility.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | /** 9 | * 10 | * @author jtherrell 11 | */ 12 | abstract class HelpHandler { 13 | protected static final int NO_HELP_TOPIC = -1; 14 | public static Log log; 15 | 16 | protected HelpHandler successor; 17 | protected int helpTopicID; 18 | 19 | public HelpHandler(HelpHandler successor, int helpTopicID) { 20 | this.successor = successor; 21 | this.helpTopicID = helpTopicID; 22 | } 23 | 24 | public boolean hasHelpFor(int helpTopicID) { 25 | return this.helpTopicID == helpTopicID; 26 | } 27 | 28 | public void handleHelp(int helpTopicID) { 29 | log.append("In HelpHandler..."); 30 | if (successor != null) 31 | successor.handleHelp(helpTopicID); 32 | } 33 | } 34 | 35 | class HelpWidget extends HelpHandler { 36 | private HelpWidget parent; 37 | 38 | public HelpWidget(HelpWidget widget, int helpTopicID) { 39 | super(widget, helpTopicID); 40 | parent = widget; 41 | } 42 | } 43 | 44 | class HelpButton extends HelpWidget { 45 | public HelpButton(HelpWidget widget, int helpTopicID) { 46 | super(widget, helpTopicID); 47 | } 48 | 49 | @Override 50 | public void handleHelp(int helpTopicID) { 51 | log.append("In HelpButton..."); 52 | if (hasHelpFor(helpTopicID)) { 53 | log.append("Button helped!"); 54 | } else { 55 | super.handleHelp(helpTopicID); 56 | } 57 | } 58 | } 59 | 60 | class HelpDialog extends HelpWidget { 61 | public HelpDialog(HelpWidget widget, int helpTopicID) { 62 | super(widget, helpTopicID); 63 | } 64 | 65 | @Override 66 | public void handleHelp(int helpTopicID) { 67 | log.append("In HelpDialog..."); 68 | if (hasHelpFor(helpTopicID)) { 69 | log.append("Dialog helped!"); 70 | } else { 71 | super.handleHelp(helpTopicID); 72 | } 73 | } 74 | } 75 | 76 | class HelpApplication extends HelpWidget { 77 | public HelpApplication(int helpTopicID) { 78 | super(null, helpTopicID); 79 | } 80 | 81 | @Override 82 | public void handleHelp(int helpTopicID) { 83 | log.append("In HelpApplication..."); 84 | if (hasHelpFor(helpTopicID)) { 85 | log.append("Application helped!"); 86 | } else { 87 | super.handleHelp(helpTopicID); 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /Java/test/designpatterns/CompositeTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import org.junit.Test; 9 | import static org.junit.Assert.*; 10 | 11 | /** 12 | * 13 | * @author jtherrell 14 | */ 15 | public class CompositeTest { 16 | 17 | /** 18 | * Test 19 | */ @Test 20 | public void testPictureAddingLine() { 21 | Graphic compositeObj = new Picture(); 22 | boolean result = compositeObj.add(new Line()); 23 | boolean expResult = true; 24 | assertEquals(expResult, result); 25 | } 26 | 27 | /** 28 | * Test 29 | */ @Test 30 | public void testPictureAddingRectangle() { 31 | Graphic compositeObj = new Picture(); 32 | boolean result = compositeObj.add(new Rectangle()); 33 | boolean expResult = true; 34 | assertEquals(expResult, result); 35 | } 36 | 37 | /** 38 | * Test 39 | */ @Test 40 | public void testPictureAddingText() { 41 | Graphic compositeObj = new Picture(); 42 | boolean result = compositeObj.add(new Text()); 43 | boolean expResult = true; 44 | assertEquals(expResult, result); 45 | } 46 | 47 | /** 48 | * Test 49 | */ @Test 50 | public void testPictureRemoval() { 51 | Graphic compositeObj = new Picture(); 52 | Graphic textObj = new Text(); 53 | compositeObj.add(textObj); 54 | boolean result = compositeObj.remove(textObj); 55 | boolean expResult = true; 56 | assertEquals(expResult, result); 57 | } 58 | 59 | /** 60 | * Test 61 | */ @Test 62 | public void testPictureGetChild() { 63 | Graphic compositeObj = new Picture(); 64 | Graphic textObj = new Text(); 65 | compositeObj.add(textObj); 66 | Graphic returnedTextObj = compositeObj.getChild(0); 67 | assertEquals(textObj, returnedTextObj); 68 | } 69 | 70 | /** 71 | * Test 72 | */ @Test 73 | public void testPictureDraw() { 74 | Log log = new Log(); 75 | Graphic compositeObj = new Picture(); 76 | // We'll add a Picture in the Picture along with a standalone Graphic 77 | // such as Line. 78 | Graphic threeRectanglePicture = new Picture(); 79 | threeRectanglePicture.add(new Rectangle()); 80 | threeRectanglePicture.add(new Rectangle()); 81 | threeRectanglePicture.add(new Rectangle()); 82 | compositeObj.add(threeRectanglePicture); 83 | compositeObj.add(new Line()); 84 | compositeObj.add(new Text()); 85 | compositeObj.draw(log); 86 | String expResult = "RectRectRectLineText"; 87 | String result = log.toString(); 88 | assertEquals(expResult, result); 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /Java/src/designpatterns/Bridge.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | import java.awt.Point; 8 | import java.awt.Rectangle; 9 | 10 | /** 11 | * 12 | * @author jtherrell 13 | */ 14 | abstract class Window { 15 | protected WindowImp implementation; 16 | protected Log log; 17 | protected Rectangle boundingBox; 18 | 19 | public void drawText() { 20 | implementation.drawText(); 21 | } 22 | 23 | public void drawRect() { 24 | Point p1 = boundingBox.getLocation(); 25 | Point p2 = new Point(p1.x, p1.y + boundingBox.height); 26 | Point p3 = new Point(p1.x + boundingBox.width, p1.y + boundingBox.height); 27 | Point p4 = new Point(p1.x + boundingBox.width, p1.y); 28 | implementation.drawLine(p1, p2); 29 | implementation.drawLine(p2,p3); 30 | implementation.drawLine(p3,p4); 31 | implementation.drawLine(p4,p1); 32 | } 33 | } 34 | 35 | class IconWindow extends Window { 36 | public IconWindow(Log l) { 37 | log = l; 38 | implementation = WindowImp.getWindowImp(0); 39 | implementation.attachLog(log); 40 | boundingBox = new Rectangle(10,10); 41 | } 42 | public void draw() { 43 | drawRect(); 44 | drawText(); 45 | } 46 | } 47 | 48 | class TransientWindow extends Window { 49 | public TransientWindow(Log l) { 50 | log = l; 51 | implementation = WindowImp.getWindowImp(1); 52 | implementation.attachLog(log); 53 | boundingBox = new Rectangle(10,10); 54 | } 55 | public void draw() { 56 | drawRect(); 57 | } 58 | } 59 | 60 | abstract class WindowImp { 61 | protected Log log; 62 | abstract public void drawText(); 63 | abstract public void drawLine(Point p1, Point p2); 64 | public void attachLog(Log log) { 65 | this.log = log; 66 | } 67 | static WindowImp getWindowImp(int context) { 68 | return context < 1 ? new XWindowImp() : new YWindowImp(); 69 | } 70 | } 71 | 72 | class XWindowImp extends WindowImp { 73 | public void drawText() { log.append("world"); } 74 | public void drawLine(Point p1, Point p2) { log.append("hello"); } 75 | } 76 | 77 | class YWindowImp extends WindowImp { 78 | public void drawText() { log.append("neato"); } 79 | public void drawLine(Point p1, Point p2) { log.append("wow"); } 80 | } 81 | 82 | class Log { 83 | private StringBuffer log; 84 | public Log() { 85 | log = new StringBuffer(); 86 | } 87 | public void append(char c) { 88 | log.append(c); 89 | } 90 | public void append(String s) { 91 | log.append(s); 92 | } 93 | @Override 94 | public String toString() { 95 | return log.toString(); 96 | } 97 | } -------------------------------------------------------------------------------- /Java/nbproject/project.properties: -------------------------------------------------------------------------------- 1 | annotation.processing.enabled=true 2 | annotation.processing.enabled.in.editor=false 3 | annotation.processing.processor.options= 4 | annotation.processing.processors.list= 5 | annotation.processing.run.all.processors=true 6 | annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output 7 | build.classes.dir=${build.dir}/classes 8 | build.classes.excludes=**/*.java,**/*.form 9 | # This directory is removed when the project is cleaned: 10 | build.dir=build 11 | build.generated.dir=${build.dir}/generated 12 | build.generated.sources.dir=${build.dir}/generated-sources 13 | # Only compile against the classpath explicitly listed here: 14 | build.sysclasspath=ignore 15 | build.test.classes.dir=${build.dir}/test/classes 16 | build.test.results.dir=${build.dir}/test/results 17 | # Uncomment to specify the preferred debugger connection transport: 18 | #debug.transport=dt_socket 19 | debug.classpath=\ 20 | ${run.classpath} 21 | debug.test.classpath=\ 22 | ${run.test.classpath} 23 | # This directory is removed when the project is cleaned: 24 | dist.dir=dist 25 | dist.jar=${dist.dir}/DesignPatterns.jar 26 | dist.javadoc.dir=${dist.dir}/javadoc 27 | excludes= 28 | includes=** 29 | jar.compress=false 30 | javac.classpath= 31 | # Space-separated list of extra javac options 32 | javac.compilerargs= 33 | javac.deprecation=false 34 | javac.processorpath=\ 35 | ${javac.classpath} 36 | javac.source=1.5 37 | javac.target=1.5 38 | javac.test.classpath=\ 39 | ${javac.classpath}:\ 40 | ${build.classes.dir}:\ 41 | ${libs.junit_4.classpath} 42 | javac.test.processorpath=\ 43 | ${javac.test.classpath} 44 | javadoc.additionalparam= 45 | javadoc.author=false 46 | javadoc.encoding=${source.encoding} 47 | javadoc.noindex=false 48 | javadoc.nonavbar=false 49 | javadoc.notree=false 50 | javadoc.private=false 51 | javadoc.splitindex=true 52 | javadoc.use=true 53 | javadoc.version=false 54 | javadoc.windowtitle= 55 | main.class=designpatterns.Main 56 | manifest.file=manifest.mf 57 | meta.inf.dir=${src.dir}/META-INF 58 | platform.active=default_platform 59 | run.classpath=\ 60 | ${javac.classpath}:\ 61 | ${build.classes.dir} 62 | # Space-separated list of JVM arguments used when running the project 63 | # (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value 64 | # or test-sys-prop.name=value to set system properties for unit tests): 65 | run.jvmargs= 66 | run.test.classpath=\ 67 | ${javac.test.classpath}:\ 68 | ${build.test.classes.dir} 69 | source.encoding=UTF-8 70 | src.dir=src 71 | test.src.dir=test 72 | -------------------------------------------------------------------------------- /C++/decorator.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | */ 3 | class VisualComponent; 4 | class Window { 5 | public: 6 | void SetContents (VisualComponent* contents); 7 | }; 8 | /* 9 | */ 10 | class VisualComponent { 11 | public: 12 | VisualComponent(); 13 | 14 | virtual void Draw(); 15 | virtual void Resize(); 16 | // ... 17 | }; 18 | /* 19 | */ 20 | class Decorator : public VisualComponent { 21 | public: 22 | Decorator(VisualComponent*); 23 | /* 24 | */ 25 | virtual void Draw(); 26 | virtual void Resize(); 27 | // ... 28 | private: 29 | VisualComponent* _component; 30 | }; 31 | /* 32 | */ 33 | void Decorator::Draw () { 34 | _component->Draw(); 35 | } 36 | 37 | void Decorator::Resize () { 38 | _component->Resize(); 39 | } 40 | /* 41 | */ 42 | class BorderDecorator : public Decorator { 43 | public: 44 | BorderDecorator(VisualComponent*, int borderWidth); 45 | 46 | virtual void Draw(); 47 | private: 48 | void DrawBorder(int); 49 | private: 50 | int _width; 51 | }; 52 | /* 53 | */ 54 | void BorderDecorator::Draw () { 55 | Decorator::Draw(); 56 | DrawBorder(_width); 57 | } 58 | /* 59 | */ 60 | void Window::SetContents (VisualComponent* contents) { 61 | // ... 62 | } 63 | /* 64 | */ 65 | class ScrollDecorator : public Decorator { 66 | public: 67 | ScrollDecorator(VisualComponent*); 68 | }; 69 | 70 | class TextView : public VisualComponent { 71 | }; 72 | //main () { 73 | ///* 74 | //*/ 75 | //Window* window = new Window; 76 | //TextView* textView = new TextView; 77 | ///* 78 | //*/ 79 | //window->SetContents(textView); 80 | ///* 81 | //*/ 82 | //window->SetContents( 83 | // new BorderDecorator( 84 | // new ScrollDecorator(textView), 1 85 | // ) 86 | //); 87 | ///* 88 | //*/ 89 | //} 90 | /* 91 | */ 92 | class Stream { 93 | public: 94 | virtual void PutInt(int); 95 | virtual void PutString(const char*); 96 | }; 97 | 98 | class StreamDecorator : public Stream { 99 | public: 100 | StreamDecorator(Stream*); 101 | private: 102 | Stream* _component; 103 | }; 104 | 105 | class CompressingStream : public StreamDecorator { 106 | public: 107 | CompressingStream(Stream*); 108 | }; 109 | 110 | class ASCII7Stream : public Stream { 111 | public: 112 | ASCII7Stream(Stream*); 113 | }; 114 | class FileStream : public Stream { 115 | public: 116 | FileStream(const char*); 117 | }; 118 | 119 | void dummy() { 120 | 121 | /* 122 | */ 123 | Stream* aStream = new CompressingStream( 124 | new ASCII7Stream( 125 | new FileStream("aFileName") 126 | ) 127 | ); 128 | aStream->PutInt(12); 129 | aStream->PutString("aString"); 130 | /* 131 | */ 132 | } 133 | /* 134 | */ 135 | -------------------------------------------------------------------------------- /C++/flyweight.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | */ 3 | #include "defs.h" 4 | class Window; 5 | class GlyphContext; 6 | class Font { 7 | public: 8 | Font(char*); 9 | }; 10 | class BTree; 11 | /* 12 | */ 13 | class Glyph { 14 | public: 15 | virtual ~Glyph(); 16 | 17 | virtual void Draw(Window*, GlyphContext&); 18 | /* 19 | */ 20 | virtual void SetFont(Font*, GlyphContext&); 21 | virtual Font* GetFont(GlyphContext&); 22 | /* 23 | */ 24 | virtual void First(GlyphContext&); 25 | virtual void Next(GlyphContext&); 26 | virtual bool IsDone(GlyphContext&); 27 | virtual Glyph* Current(GlyphContext&); 28 | /* 29 | */ 30 | virtual void Insert(Glyph*, GlyphContext&); 31 | virtual void Remove(GlyphContext&); 32 | protected: 33 | Glyph(); 34 | }; 35 | /* 36 | */ 37 | class Character : public Glyph { 38 | public: 39 | Character(char); 40 | 41 | virtual void Draw(Window*, GlyphContext&); 42 | private: 43 | char _charcode; 44 | }; 45 | /* 46 | */ 47 | class GlyphContext { 48 | public: 49 | GlyphContext(); 50 | virtual ~GlyphContext(); 51 | /* 52 | */ 53 | virtual void Next(int step = 1); 54 | virtual void Insert(int quantity = 1); 55 | /* 56 | */ 57 | virtual Font* GetFont(); 58 | virtual void SetFont(Font*, int span = 1); 59 | private: 60 | int _index; 61 | BTree* _fonts; 62 | }; 63 | /* 64 | */ 65 | void dummy () { 66 | /* 67 | */ 68 | GlyphContext gc; 69 | Font* times12 = new Font("Times-Roman-12"); 70 | Font* timesItalic12 = new Font("Times-Italic-12"); 71 | // ... 72 | 73 | gc.SetFont(times12, 6); 74 | /* 75 | */ 76 | gc.Insert(6); 77 | gc.SetFont(timesItalic12, 6); 78 | /* 79 | */ 80 | } 81 | /* 82 | */ 83 | class Row { 84 | }; 85 | class Column { 86 | }; 87 | /* 88 | */ 89 | const int NCHARCODES = 128; 90 | 91 | class GlyphFactory { 92 | public: 93 | GlyphFactory(); 94 | virtual ~GlyphFactory(); 95 | /* 96 | */ 97 | virtual Character* CreateCharacter(char); 98 | virtual Row* CreateRow(); 99 | virtual Column* CreateColumn(); 100 | // ... 101 | private: 102 | Character* _character[NCHARCODES]; 103 | }; 104 | /* 105 | */ 106 | GlyphFactory::GlyphFactory () { 107 | for (int i = 0; i < NCHARCODES; ++i) { 108 | _character[i] = 0; 109 | } 110 | } 111 | /* 112 | */ 113 | Character* GlyphFactory::CreateCharacter (char c) { 114 | if (!_character[c]) { 115 | _character[c] = new Character(c); 116 | } 117 | 118 | return _character[c]; 119 | } 120 | /* 121 | */ 122 | Row* GlyphFactory::CreateRow () { 123 | return new Row; 124 | } 125 | /* 126 | */ 127 | Column* GlyphFactory::CreateColumn () { 128 | return new Column; 129 | } 130 | /* 131 | */ 132 | -------------------------------------------------------------------------------- /C++/mediator.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | */ 3 | #include "List.h" 4 | class MouseEvent; 5 | class Widget; 6 | 7 | /* 8 | */ 9 | class DialogDirector { 10 | public: 11 | virtual ~DialogDirector(); 12 | 13 | virtual void ShowDialog(); 14 | virtual void WidgetChanged(Widget*) = 0; 15 | /* 16 | */ 17 | protected: 18 | DialogDirector(); 19 | virtual void CreateWidgets() = 0; 20 | }; 21 | /* 22 | */ 23 | class Widget { 24 | public: 25 | Widget(DialogDirector*); 26 | virtual void Changed(); 27 | 28 | virtual void HandleMouse(MouseEvent& event); 29 | // ... 30 | private: 31 | DialogDirector* _director; 32 | }; 33 | /* 34 | */ 35 | void Widget::Changed () { 36 | _director->WidgetChanged(this); 37 | } 38 | /* 39 | */ 40 | class ListBox : public Widget { 41 | public: 42 | ListBox(DialogDirector*); 43 | 44 | virtual const char* GetSelection(); 45 | virtual void SetList(List* listItems); 46 | virtual void HandleMouse(MouseEvent& event); 47 | // ... 48 | }; 49 | /* 50 | */ 51 | class EntryField : public Widget { 52 | public: 53 | EntryField(DialogDirector*); 54 | 55 | virtual void SetText(const char* text); 56 | virtual const char* GetText(); 57 | virtual void HandleMouse(MouseEvent& event); 58 | // ... 59 | }; 60 | /* 61 | */ 62 | class Button : public Widget { 63 | public: 64 | Button(DialogDirector*); 65 | 66 | virtual void SetText(const char* text); 67 | virtual void HandleMouse(MouseEvent& event); 68 | // ... 69 | }; 70 | /* 71 | */ 72 | void Button::HandleMouse (MouseEvent& event) { 73 | // ... 74 | Changed(); 75 | } 76 | /* 77 | */ 78 | class FontDialogDirector : public DialogDirector { 79 | public: 80 | FontDialogDirector(); 81 | virtual ~FontDialogDirector(); 82 | virtual void WidgetChanged(Widget*); 83 | /* 84 | */ 85 | protected: 86 | virtual void CreateWidgets(); 87 | /* 88 | */ 89 | private: 90 | Button* _ok; 91 | Button* _cancel; 92 | ListBox* _fontList; 93 | EntryField* _fontName; 94 | }; 95 | /* 96 | */ 97 | void FontDialogDirector::CreateWidgets () { 98 | _ok = new Button(this); 99 | _cancel = new Button(this); 100 | _fontList = new ListBox(this); 101 | _fontName = new EntryField(this); 102 | 103 | // fill the listBox with the available font names 104 | 105 | // assemble the widgets in the dialog 106 | } 107 | /* 108 | */ 109 | void FontDialogDirector::WidgetChanged ( 110 | Widget* theChangedWidget 111 | ) { 112 | if (theChangedWidget == _fontList) { 113 | _fontName->SetText(_fontList->GetSelection()); 114 | /* 115 | */ 116 | } else if (theChangedWidget == _ok) { 117 | // apply font change and dismiss dialog 118 | // ... 119 | /* 120 | */ 121 | } else if (theChangedWidget == _cancel) { 122 | // dismiss dialog 123 | } 124 | } 125 | /* 126 | */ 127 | -------------------------------------------------------------------------------- /Java/src/designpatterns/Command.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | /** 12 | * 13 | * @author jtherrell 14 | */ 15 | class Application { 16 | private List docs; 17 | private int currentDocIndex; 18 | private Menu menu; 19 | private Log log; 20 | 21 | public Application(Log log) { 22 | docs = new ArrayList(); 23 | currentDocIndex = -1; 24 | this.log = log; 25 | } 26 | 27 | public void addMenu(Menu menu) { 28 | this.menu = menu; 29 | } 30 | 31 | public void addDocument(Document doc) { 32 | log.append(doc.filename() + " opened..."); 33 | docs.add(doc); 34 | currentDocIndex = docs.indexOf(doc); 35 | } 36 | 37 | public Document currentDoc() { 38 | if (currentDocIndex < 0 || currentDocIndex >= docs.size()) { 39 | return null; 40 | } 41 | log.append("Paste to " + docs.get(currentDocIndex).filename()); 42 | return docs.get(currentDocIndex); 43 | } 44 | } 45 | /* 46 | */ 47 | interface Command { 48 | public void execute(); 49 | } 50 | /* 51 | */ 52 | class OpenCommand implements Command { 53 | 54 | private Application target; 55 | 56 | public OpenCommand(Application app) { 57 | target = app; 58 | } 59 | 60 | public void execute() { 61 | String name = askUser(); 62 | if(name != null) { 63 | Document doc = new Document(name); 64 | target.addDocument(doc); 65 | doc.open(); 66 | } 67 | } 68 | 69 | public String askUser() { 70 | // Pretend we prompt the user for the filename 71 | return "./untitled.txt"; 72 | } 73 | } 74 | 75 | 76 | class PasteCommand implements Command { 77 | private Application target; 78 | 79 | public PasteCommand(Application target) { 80 | this.target = target; 81 | } 82 | 83 | public void execute() { 84 | target.currentDoc().paste(); 85 | } 86 | } 87 | 88 | class Menu { 89 | private List menuItems; 90 | 91 | public Menu() { 92 | menuItems = new ArrayList(); 93 | } 94 | 95 | public void addMenuItem(MenuItem menuItem) { 96 | if (menuItem != null) 97 | menuItems.add(menuItem); 98 | } 99 | } 100 | 101 | class MenuItem { 102 | private String label; 103 | private Command command; 104 | 105 | public MenuItem(String label, Command command) { 106 | this.label = label; 107 | this.command = command; 108 | } 109 | 110 | public void clicked() { 111 | command.execute(); 112 | } 113 | 114 | } 115 | 116 | class Document { 117 | private String filename; 118 | 119 | public Document(String filename) { 120 | this.filename = filename; 121 | } 122 | 123 | public String filename() { 124 | return filename; 125 | } 126 | 127 | public void read() {} 128 | public void open() {} 129 | public void paste() {} 130 | } -------------------------------------------------------------------------------- /C++/MazeParts.h: -------------------------------------------------------------------------------- 1 | #ifndef MazeParts_H 2 | #define MazeParts_H 3 | 4 | #include "defs.h" 5 | 6 | enum Direction { North, East, South, West }; 7 | #ifndef MapSite_H 8 | #define MapSite_H 9 | 10 | class MapSite { 11 | public: 12 | virtual void Enter() = 0; 13 | }; 14 | 15 | #endif 16 | #ifndef _H 17 | #define _H 18 | 19 | class Room : public MapSite { 20 | public: 21 | Room(int = 0); 22 | Room(const Room&); 23 | 24 | virtual Room* Clone() const; 25 | void InitializeRoomNo(int); 26 | 27 | MapSite* GetSide(Direction); 28 | void SetSide(Direction, MapSite*); 29 | 30 | virtual void Enter(); 31 | private: 32 | MapSite* _sides[4]; 33 | int _roomNumber; 34 | }; 35 | #endif 36 | #ifndef Wall_H 37 | #define Wall_H 38 | 39 | class Wall : public MapSite { 40 | public: 41 | 42 | Wall(); 43 | Wall(const Wall&); 44 | virtual Wall* Clone() const; 45 | virtual void Enter(); 46 | }; 47 | #endif 48 | #ifndef Door_H 49 | #define Door_H 50 | 51 | class Door : public MapSite { 52 | public: 53 | Door(Room* = 0, Room* = 0); 54 | Door(const Room&); 55 | 56 | virtual Door* Clone() const; 57 | void Initialize(Room*, Room*); 58 | 59 | virtual void Enter(); 60 | Room* OtherSideFrom(Room*); 61 | private: 62 | Room* _room1; 63 | Room* _room2; 64 | bool _isOpen; 65 | }; 66 | #endif 67 | #ifndef Maze_H 68 | #define Maze_H 69 | 70 | class Maze { 71 | public: 72 | Maze(); 73 | Maze(const Maze&); 74 | Room* RoomNo(int); 75 | void AddRoom(Room*); 76 | 77 | virtual Maze* Clone() const; 78 | private: 79 | // ... 80 | }; 81 | #endif 82 | #ifndef BombedWall_H 83 | #define BombedWall_H 84 | 85 | class BombedWall : public Wall { 86 | public: 87 | BombedWall(bool bombed = false); 88 | BombedWall(const BombedWall&); 89 | 90 | virtual Wall* Clone() const; 91 | void Intialize(bool); 92 | 93 | virtual void Enter(); 94 | private: 95 | bool _bomb; 96 | }; 97 | #endif 98 | #ifndef RoomWithABomb_H 99 | #define RoomWithABomb_H 100 | 101 | class RoomWithABomb: public Room { 102 | public: 103 | RoomWithABomb(int = 0, bool bombed = false); 104 | RoomWithABomb(const RoomWithABomb&); 105 | bool HasBomb(); 106 | private: 107 | bool _bomb; 108 | }; 109 | 110 | #endif 111 | #ifndef EnchantedRoom_H 112 | #define EnchantedRoom_H 113 | 114 | class Spell; 115 | 116 | class EnchantedRoom : public Room { 117 | public: 118 | EnchantedRoom(int, Spell* = 0); 119 | EnchantedRoom(const EnchantedRoom&); 120 | bool HasSpell(); 121 | Spell PickUpSpell(); 122 | private: 123 | Spell* _spell; 124 | }; 125 | 126 | #endif 127 | #ifndef DoorNeedingSpell_H 128 | #define DoorNeedingSpell_H 129 | 130 | class DoorNeedingSpell : public Door { 131 | public: 132 | DoorNeedingSpell(Room*, Room*); 133 | DoorNeedingSpell(const DoorNeedingSpell&); 134 | bool TrySpell(Spell); 135 | }; 136 | #endif 137 | 138 | 139 | #endif 140 | -------------------------------------------------------------------------------- /C++/prototype.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | */ 3 | #ifdef SampleCode1 4 | #include "MazeGame.h" 5 | #include "MazeFactory.h" 6 | #include "MazeParts.h" 7 | /* 8 | */ 9 | class MazePrototypeFactory : public MazeFactory { 10 | public: 11 | MazePrototypeFactory(Maze*, Wall*, Room*, Door*); 12 | /* 13 | */ 14 | virtual Maze* MakeMaze() const; 15 | virtual Room* MakeRoom(int) const; 16 | virtual Wall* MakeWall() const; 17 | virtual Door* MakeDoor(Room*, Room*) const; 18 | /* 19 | */ 20 | private: 21 | Maze* _prototypeMaze; 22 | Room* _prototypeRoom; 23 | Wall* _prototypeWall; 24 | Door* _prototypeDoor; 25 | }; 26 | /* 27 | */ 28 | MazePrototypeFactory::MazePrototypeFactory ( 29 | Maze* m, Wall* w, Room* r, Door* d 30 | ) { 31 | _prototypeMaze = m; 32 | _prototypeWall = w; 33 | _prototypeRoom = r; 34 | _prototypeDoor = d; 35 | } 36 | /* 37 | */ 38 | Wall* MazePrototypeFactory::MakeWall () const { 39 | return _prototypeWall->Clone(); 40 | } 41 | /* 42 | */ 43 | Door* MazePrototypeFactory::MakeDoor (Room* r1, Room *r2) const { 44 | Door* door = _prototypeDoor->Clone(); 45 | door->Initialize(r1, r2); 46 | return door; 47 | } 48 | /* 49 | */ 50 | void dummy () { 51 | /* 52 | */ 53 | MazeGame game; 54 | MazePrototypeFactory simpleMazeFactory( 55 | new Maze, new Wall, new Room, new Door 56 | ); 57 | 58 | Maze* maze = game.CreateMaze(simpleMazeFactory); 59 | /* 60 | */ 61 | } 62 | void dummy2 () { 63 | /* 64 | */ 65 | MazePrototypeFactory bombedMazeFactory( 66 | new Maze, new BombedWall, 67 | new RoomWithABomb, new Door 68 | ); 69 | /* 70 | */ 71 | } 72 | #endif 73 | #ifdef SampleCode2 74 | #define Door_H 75 | #define BombedWall_H 76 | #define DoorNeedingSpell_H 77 | #include "MazeParts.h" 78 | /* 79 | */ 80 | class Door : public MapSite { 81 | public: 82 | Door(); 83 | Door(const Door&); 84 | /* 85 | */ 86 | virtual void Initialize(Room*, Room*); 87 | virtual Door* Clone() const; 88 | /* 89 | */ 90 | virtual void Enter(); 91 | Room* OtherSideFrom(Room*); 92 | private: 93 | Room* _room1; 94 | Room* _room2; 95 | }; 96 | /* 97 | */ 98 | Door::Door (const Door& other) { 99 | _room1 = other._room1; 100 | _room2 = other._room2; 101 | } 102 | /* 103 | */ 104 | void Door::Initialize (Room* r1, Room* r2) { 105 | _room1 = r1; 106 | _room2 = r2; 107 | } 108 | /* 109 | */ 110 | Door* Door::Clone () const { 111 | return new Door(*this); 112 | } 113 | /* 114 | */ 115 | class BombedWall : public Wall { 116 | public: 117 | BombedWall(); 118 | BombedWall(const BombedWall&); 119 | /* 120 | */ 121 | virtual Wall* Clone() const; 122 | bool HasBomb(); 123 | private: 124 | bool _bomb; 125 | }; 126 | /* 127 | */ 128 | BombedWall::BombedWall (const BombedWall& other) : Wall(other) { 129 | _bomb = other._bomb; 130 | } 131 | /* 132 | */ 133 | Wall* BombedWall::Clone () const { 134 | return new BombedWall(*this); 135 | } 136 | /* 137 | */ 138 | #endif 139 | /* 140 | */ 141 | -------------------------------------------------------------------------------- /C++/singleton.cpp: -------------------------------------------------------------------------------- 1 | #include "defs.h" 2 | /* 3 | */ 4 | #ifdef Implementation1 5 | /* 6 | */ 7 | class Singleton { 8 | public: 9 | static Singleton* Instance(); 10 | protected: 11 | Singleton(); 12 | private: 13 | static Singleton* _instance; 14 | }; 15 | /* 16 | */ 17 | Singleton* Singleton::_instance = 0; 18 | 19 | Singleton* Singleton::Instance () { 20 | if (_instance == 0) { 21 | _instance = new Singleton; 22 | } 23 | return _instance; 24 | } 25 | /* 26 | */ 27 | #endif 28 | /* 29 | */ 30 | #ifdef Implementation2 31 | #include "List.h" 32 | #include "stdlib.h" 33 | class NameSingletonPair; 34 | 35 | /* 36 | */ 37 | class Singleton { 38 | public: 39 | static void Register(char* name, Singleton*); 40 | static Singleton* Instance(); 41 | protected: 42 | static Singleton* Lookup(const char* name); 43 | private: 44 | static Singleton* _instance; 45 | static List* _registry; 46 | }; 47 | /* 48 | */ 49 | Singleton* Singleton::Instance () { 50 | if (_instance == 0) { 51 | const char* singletonName = getenv("SINGLETON"); 52 | // user or environment supplies this at startup 53 | 54 | _instance = Lookup(singletonName); 55 | // Lookup returns 0 if there's no such singleton 56 | } 57 | return _instance; 58 | } 59 | /* 60 | */ 61 | class MySingleton : public Singleton { 62 | public: 63 | MySingleton(); 64 | }; 65 | /* 66 | */ 67 | MySingleton::MySingleton() { 68 | // ... 69 | Singleton::Register("MySingleton", this); 70 | } 71 | /* 72 | */ 73 | static MySingleton theSingleton; 74 | /* 75 | */ 76 | #endif 77 | /* 78 | */ 79 | #ifdef Singleton 80 | /* 81 | */ 82 | class MazeFactory { 83 | public: 84 | static MazeFactory* Instance(); 85 | 86 | // existing interface goes here 87 | protected: 88 | MazeFactory(); 89 | private: 90 | static MazeFactory* _instance; 91 | }; 92 | /* 93 | */ 94 | MazeFactory* MazeFactory::_instance = 0; 95 | 96 | MazeFactory* MazeFactory::Instance () { 97 | if (_instance == 0) { 98 | _instance = new MazeFactory; 99 | } 100 | return _instance; 101 | } 102 | /* 103 | */ 104 | #else 105 | //MazeFactory* MazeFactory::_instance = 0; 106 | #include "MazeFactories.h" 107 | #include "stdlib.h" 108 | #include "strings.h" 109 | /* 110 | */ 111 | MazeFactory* MazeFactory::Instance () { 112 | if (_instance == 0) { 113 | const char* mazeStyle = getenv("MAZESTYLE"); 114 | /* 115 | */ 116 | if (strcmp(mazeStyle, "bombed") == 0) { 117 | _instance = new BombedMazeFactory; 118 | /* 119 | */ 120 | } else if (strcmp(mazeStyle, "enchanted") == 0) { 121 | _instance = new EnchantedMazeFactory; 122 | /* 123 | */ 124 | // ... other possible subclasses 125 | /* 126 | */ 127 | } else { // default 128 | _instance = new MazeFactory; 129 | } 130 | } 131 | return _instance; 132 | } 133 | /* 134 | */ 135 | #endif 136 | /* 137 | */ 138 | -------------------------------------------------------------------------------- /C++/adapter.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | */ 3 | #include "Geom.h" 4 | // Compilation Instructions 5 | // With ClassAdapter defined and not defined 6 | #define ClassAdapter 0 7 | /* 8 | */ 9 | class Manipulator; 10 | /* 11 | */ 12 | class Shape { 13 | public: 14 | Shape(); 15 | virtual void BoundingBox( 16 | Point& bottomLeft, Point& topRight 17 | ) const; 18 | virtual Manipulator* CreateManipulator() const; 19 | }; 20 | /* 21 | */ 22 | class TextView { 23 | public: 24 | TextView(); 25 | void GetOrigin(Coord& x, Coord& y) const; 26 | void GetExtent(Coord& width, Coord& height) const; 27 | virtual bool IsEmpty() const; 28 | }; 29 | /* 30 | */ 31 | #ifdef ClassAdapter 32 | /* 33 | */ 34 | class TextShape : public Shape, private TextView { 35 | public: 36 | TextShape(); 37 | 38 | virtual void BoundingBox( 39 | Point& bottomLeft, Point& topRight 40 | ) const; 41 | virtual bool IsEmpty() const; 42 | virtual Manipulator* CreateManipulator() const; 43 | }; 44 | /* 45 | */ 46 | void TextShape::BoundingBox ( 47 | Point& bottomLeft, Point& topRight 48 | ) const { 49 | Coord bottom, left, width, height; 50 | 51 | GetOrigin(bottom, left); 52 | GetExtent(width, height); 53 | /* 54 | */ 55 | bottomLeft = Point(bottom, left); 56 | topRight = Point(bottom + height, left + width); 57 | } 58 | /* 59 | */ 60 | bool TextShape::IsEmpty () const { 61 | return TextView::IsEmpty(); 62 | } 63 | /* 64 | */ 65 | class Manipulator { 66 | }; 67 | class TextManipulator : public Manipulator { 68 | public: 69 | TextManipulator(const TextShape*); 70 | }; 71 | /* 72 | */ 73 | Manipulator* TextShape::CreateManipulator () const { 74 | return new TextManipulator(this); 75 | } 76 | /* 77 | */ 78 | #endif 79 | #ifndef ClassAdapter 80 | class TextView; 81 | class Manipulator { 82 | }; 83 | class TextManipulator : public Manipulator { 84 | public: 85 | TextManipulator(); 86 | }; 87 | /* 88 | */ 89 | class TextShape : public Shape { 90 | public: 91 | TextShape(TextView*); 92 | 93 | virtual void BoundingBox( 94 | Point& bottomLeft, Point& topRight 95 | ) const; 96 | virtual bool IsEmpty() const; 97 | virtual Manipulator* CreateManipulator() const; 98 | private: 99 | TextView* _text; 100 | }; 101 | /* 102 | */ 103 | TextShape::TextShape (TextView* t) { 104 | _text = t; 105 | } 106 | /* 107 | */ 108 | void TextShape::BoundingBox ( 109 | Point& bottomLeft, Point& topRight 110 | ) const { 111 | Coord bottom, left, width, height; 112 | 113 | _text->GetOrigin(bottom, left); 114 | _text->GetExtent(width, height); 115 | 116 | bottomLeft = Point(bottom, left); 117 | topRight = Point(bottom + height, left + width); 118 | } 119 | /* 120 | */ 121 | bool TextShape::IsEmpty () const { 122 | return _text->IsEmpty(); 123 | } 124 | /* 125 | */ 126 | Manipulator* TextShape::CreateManipulator () const { 127 | return new TextManipulator(this); 128 | } 129 | /* 130 | */ 131 | #endif 132 | /* 133 | */ 134 | -------------------------------------------------------------------------------- /C++/command.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | */ 3 | #include "List.h" 4 | 5 | class Document { 6 | public: 7 | Document(const char*); 8 | void Open(); 9 | void Paste(); 10 | }; 11 | 12 | class Application { 13 | public: 14 | Application(); 15 | void Add(Document*); 16 | }; 17 | /* 18 | */ 19 | class Command { 20 | public: 21 | virtual ~Command(); 22 | 23 | virtual void Execute() = 0; 24 | protected: 25 | Command(); 26 | }; 27 | /* 28 | */ 29 | class OpenCommand : public Command { 30 | public: 31 | OpenCommand(Application*); 32 | 33 | virtual void Execute(); 34 | protected: 35 | virtual const char* AskUser(); 36 | private: 37 | Application* _application; 38 | char* _response; 39 | }; 40 | /* 41 | */ 42 | OpenCommand::OpenCommand (Application* a) { 43 | _application = a; 44 | } 45 | /* 46 | */ 47 | void OpenCommand::Execute () { 48 | const char* name = AskUser(); 49 | 50 | if (name != 0) { 51 | Document* document = new Document(name); 52 | _application->Add(document); 53 | document->Open(); 54 | } 55 | } 56 | /* 57 | */ 58 | class PasteCommand : public Command { 59 | public: 60 | PasteCommand(Document*); 61 | 62 | virtual void Execute(); 63 | private: 64 | Document* _document; 65 | }; 66 | /* 67 | */ 68 | PasteCommand::PasteCommand (Document* doc) { 69 | _document = doc; 70 | } 71 | 72 | void PasteCommand::Execute () { 73 | _document->Paste(); 74 | } 75 | /* 76 | */ 77 | template 78 | class SimpleCommand : public Command { 79 | public: 80 | typedef void (Receiver::* Action)(); 81 | 82 | SimpleCommand(Receiver* r, Action a) : 83 | _receiver(r), _action(a) { } 84 | 85 | virtual void Execute(); 86 | private: 87 | Action _action; 88 | Receiver* _receiver; 89 | }; 90 | /* 91 | */ 92 | template 93 | void SimpleCommand::Execute () { 94 | (_receiver->*_action)(); 95 | } 96 | /* 97 | */ 98 | class MyClass { 99 | public: 100 | void Action(); 101 | }; 102 | void dummy () { 103 | /* 104 | */ 105 | MyClass* receiver = new MyClass; 106 | // ... 107 | Command* aCommand = 108 | new SimpleCommand(receiver, &MyClass::Action); 109 | // ... 110 | aCommand->Execute(); 111 | /* 112 | */ 113 | } 114 | /* 115 | */ 116 | class MacroCommand : public Command { 117 | public: 118 | MacroCommand(); 119 | virtual ~MacroCommand(); 120 | 121 | virtual void Add(Command*); 122 | virtual void Remove(Command*); 123 | 124 | virtual void Execute(); 125 | private: 126 | List* _cmds; 127 | }; 128 | /* 129 | */ 130 | void MacroCommand::Execute () { 131 | ListIterator i(_cmds); 132 | 133 | for (i.First(); !i.IsDone(); i.Next()) { 134 | Command* c = i.CurrentItem(); 135 | c->Execute(); 136 | } 137 | } 138 | /* 139 | */ 140 | void MacroCommand::Add (Command* c) { 141 | _cmds->Append(c); 142 | } 143 | 144 | void MacroCommand::Remove (Command* c) { 145 | _cmds->Remove(c); 146 | } 147 | /* 148 | */ 149 | -------------------------------------------------------------------------------- /Java/src/designpatterns/State.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | /** 9 | * 10 | * @author jtherrell 11 | */ 12 | abstract class TCPState { 13 | 14 | public void transmit(TCPConnection connection, TCPOctetStream stream) {} 15 | public void activeOpen(TCPConnection connection) {} 16 | public void passiveOpen(TCPConnection connection) {} 17 | public void close(TCPConnection connection) {} 18 | public void synchronize(TCPConnection connection) {} 19 | public void acknowledge(TCPConnection connection) {} 20 | public void send(TCPConnection connection) {} 21 | public void changeState(TCPConnection connection, TCPState state) { 22 | connection.changeState(state); 23 | } 24 | } 25 | 26 | class TCPClosed extends TCPState { 27 | private static TCPState s_instance; 28 | 29 | private TCPClosed() {} 30 | 31 | public static TCPState instance() { 32 | if (s_instance == null) { 33 | s_instance = new TCPClosed(); 34 | } 35 | return s_instance; 36 | } 37 | 38 | @Override 39 | public void activeOpen(TCPConnection connection) { 40 | changeState(connection, TCPEstablished.instance()); 41 | } 42 | 43 | @Override 44 | public void passiveOpen(TCPConnection connection) { 45 | changeState(connection, TCPListen.instance()); 46 | } 47 | } 48 | 49 | class TCPEstablished extends TCPState { 50 | private static TCPState s_instance; 51 | 52 | private TCPEstablished(){} 53 | 54 | public static TCPState instance() { 55 | if (s_instance == null) { 56 | s_instance = new TCPEstablished(); 57 | } 58 | return s_instance; 59 | } 60 | 61 | @Override 62 | public void close(TCPConnection connection) { 63 | changeState(connection, TCPListen.instance()); 64 | } 65 | 66 | @Override 67 | public void transmit(TCPConnection connection, TCPOctetStream stream) { 68 | connection.processOctet(stream); 69 | } 70 | } 71 | 72 | class TCPListen extends TCPState { 73 | private static TCPState s_instance; 74 | 75 | private TCPListen(){} 76 | 77 | public static TCPState instance() { 78 | if (s_instance == null) { 79 | s_instance = new TCPListen(); 80 | } 81 | return s_instance; 82 | } 83 | 84 | @Override 85 | public void send(TCPConnection connection) { 86 | // send SYN, receive SNY, ACK, etc. 87 | changeState(connection, TCPEstablished.instance()); 88 | } 89 | } 90 | 91 | class TCPConnection{ 92 | private TCPState state; 93 | 94 | public TCPConnection() { state = TCPClosed.instance(); } 95 | public void activeOpen() { state.activeOpen(this); } 96 | public void passiveOpen() { state.passiveOpen(this); } 97 | public void close() { state.close(this); } 98 | public void send() { state.send(this); } 99 | public void acknowledge() { state.acknowledge(this); } 100 | public void syncronize() { state.synchronize(this); } 101 | public TCPState state() { return state; } 102 | 103 | public void processOctet(TCPOctetStream stream) {} 104 | protected void changeState(TCPState state) { this.state = state; } 105 | } 106 | 107 | class TCPOctetStream{} -------------------------------------------------------------------------------- /Java/test/designpatterns/IteratorTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import java.util.List; 9 | import java.util.ArrayList; 10 | import org.junit.AfterClass; 11 | import org.junit.BeforeClass; 12 | import org.junit.Test; 13 | import static org.junit.Assert.*; 14 | 15 | /** 16 | * 17 | * @author jtherrell 18 | */ 19 | public class IteratorTest { 20 | private List list; 21 | private Iterator iterator; 22 | 23 | public IteratorTest() { 24 | list = new ArrayList(); 25 | list.add("The"); 26 | list.add("official"); 27 | list.add("Iterator"); 28 | list.add("test!"); 29 | iterator = new Iterator(list); 30 | } 31 | 32 | @BeforeClass 33 | public static void setUpClass() throws Exception { 34 | } 35 | 36 | @AfterClass 37 | public static void tearDownClass() throws Exception { 38 | } 39 | 40 | /** 41 | * Test of isEmpty method, of class Iterator. 42 | */ @Test 43 | public void testIsEmptyTrue() { 44 | while (0 < list.size()) 45 | list.remove(0); 46 | boolean expResult = true; 47 | boolean result = iterator.isEmpty(); 48 | assertEquals(expResult, result); 49 | } 50 | 51 | /** 52 | * Test of isEmpty method, of class Iterator. 53 | */ @Test 54 | public void testIsEmptyFalse() { 55 | boolean expResult = false; 56 | boolean result = iterator.isEmpty(); 57 | assertEquals(expResult, result); 58 | } 59 | 60 | /** 61 | * Test of hasNext method, of class Iterator. 62 | */ @Test 63 | public void testHasNextTrue() { 64 | boolean expResult = true; 65 | boolean result = iterator.hasNext(); 66 | assertEquals(expResult, result); 67 | } 68 | 69 | /** 70 | * Test of hasNext method, of class Iterator. 71 | */ @Test 72 | public void testHasNextFalse() { 73 | boolean expResult = false; 74 | iterator.next(); 75 | iterator.next(); 76 | iterator.next(); 77 | iterator.next(); 78 | boolean result = iterator.hasNext(); 79 | assertEquals(expResult, result); 80 | } 81 | 82 | /** 83 | * Test of hasPrevious method, of class Iterator. 84 | */ @Test 85 | public void testHasPrevTrue() { 86 | iterator.next(); 87 | boolean expResult = true; 88 | boolean result = iterator.hasPrev(); 89 | assertEquals(expResult, result); 90 | } 91 | 92 | /** 93 | * Test of hasPrevious method, of class Iterator. 94 | */ @Test 95 | public void testHasPrevFalse() { 96 | boolean expResult = false; 97 | boolean result = iterator.hasPrev(); 98 | assertEquals(expResult, result); 99 | } 100 | 101 | /** 102 | * Test of next method, of class Iterator. 103 | */ @Test 104 | public void testNext() { 105 | int i = 0; 106 | while(iterator.hasNext()) { 107 | String expResult = list.get(i); 108 | String result = iterator.next(); 109 | assertEquals(expResult, result); 110 | i++; 111 | } 112 | } 113 | 114 | /** 115 | * Test of next method, of class Iterator. 116 | */ @Test 117 | public void testPrev() { 118 | iterator.next(); 119 | iterator.next(); 120 | iterator.next(); 121 | iterator.next(); 122 | int i = list.size() - 1; 123 | while(iterator.hasPrev()) { 124 | String expResult = list.get(i); 125 | String result = iterator.prev(); 126 | assertEquals(expResult, result); 127 | i--; 128 | } 129 | } 130 | 131 | } -------------------------------------------------------------------------------- /C++/facade.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | */ 3 | #include "Foundation.h" 4 | class istream; 5 | class ostream; 6 | class Token; 7 | class ProgramNodeBuilder; 8 | class ProgramNode; 9 | class StatementNode; 10 | class ExpressionNode; 11 | class CodeGenerator; 12 | class BytecodeStream; 13 | /* 14 | */ 15 | class Scanner { 16 | public: 17 | Scanner(istream&); 18 | virtual ~Scanner(); 19 | 20 | virtual Token& Scan(); 21 | private: 22 | istream& _inputStream; 23 | }; 24 | /* 25 | */ 26 | class Parser { 27 | public: 28 | Parser(); 29 | virtual ~Parser(); 30 | 31 | virtual void Parse(Scanner&, ProgramNodeBuilder&); 32 | }; 33 | /* 34 | */ 35 | class ProgramNodeBuilder { 36 | public: 37 | ProgramNodeBuilder(); 38 | /* 39 | */ 40 | virtual ProgramNode* NewVariable( 41 | char* variableName 42 | ) const; 43 | /* 44 | */ 45 | virtual ProgramNode* NewAssignment( 46 | ProgramNode* variable, ProgramNode* expression 47 | ) const; 48 | /* 49 | */ 50 | virtual ProgramNode* NewReturnStatement( 51 | ProgramNode* value 52 | ) const; 53 | /* 54 | */ 55 | virtual ProgramNode* NewCondition( 56 | ProgramNode* condition, 57 | ProgramNode* truePart, ProgramNode* falsePart 58 | ) const; 59 | // ... 60 | /* 61 | */ 62 | ProgramNode* GetRootNode(); 63 | private: 64 | ProgramNode* _node; 65 | }; 66 | /* 67 | */ 68 | class ProgramNode { 69 | public: 70 | // program node manipulation 71 | virtual void GetSourcePosition(int& line, int& index); 72 | // ... 73 | /* 74 | */ 75 | // child manipulation 76 | virtual void Add(ProgramNode*); 77 | virtual void Remove(ProgramNode*); 78 | // ... 79 | 80 | virtual void Traverse(CodeGenerator&); 81 | protected: 82 | ProgramNode(); 83 | }; 84 | /* 85 | */ 86 | class CodeGenerator { 87 | public: 88 | virtual void Visit(StatementNode*); 89 | virtual void Visit(ExpressionNode*); 90 | // ... 91 | protected: 92 | CodeGenerator(BytecodeStream&); 93 | protected: 94 | BytecodeStream& _output; 95 | }; 96 | /* 97 | */ 98 | class ExpressionNode : public ProgramNode { 99 | public: 100 | ExpressionNode(); 101 | virtual void GetSourcePosition(int& line, int& index); 102 | virtual void Add(ProgramNode*); 103 | virtual void Remove(ProgramNode*); 104 | 105 | virtual void Traverse(CodeGenerator&); 106 | protected: 107 | List* _children; 108 | }; 109 | /* 110 | */ 111 | void ExpressionNode::Traverse (CodeGenerator& cg) { 112 | cg.Visit(this); 113 | 114 | ListIterator i(_children); 115 | 116 | for (i.First(); !i.IsDone(); i.Next()) { 117 | i.CurrentItem()->Traverse(cg); 118 | } 119 | } 120 | /* 121 | */ 122 | class Compiler { 123 | public: 124 | Compiler(); 125 | 126 | virtual void Compile(istream&, BytecodeStream&); 127 | }; 128 | /* 129 | */ 130 | class RISCCodeGenerator : public CodeGenerator { 131 | public: 132 | RISCCodeGenerator(BytecodeStream&); 133 | virtual void Visit(StatementNode*); 134 | virtual void Visit(ExpressionNode*); 135 | // ... 136 | }; 137 | /* 138 | */ 139 | void Compiler::Compile ( 140 | istream& input, BytecodeStream& output 141 | ) { 142 | Scanner scanner(input); 143 | ProgramNodeBuilder builder; 144 | Parser parser; 145 | 146 | parser.Parse(scanner, builder); 147 | 148 | RISCCodeGenerator generator(output); 149 | ProgramNode* parseTree = builder.GetRootNode(); 150 | parseTree->Traverse(generator); 151 | } 152 | /* 153 | */ 154 | -------------------------------------------------------------------------------- /C++/state.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | 3 | class TCPOctetStream; 4 | class TCPState; 5 | 6 | class TCPConnection { 7 | public: 8 | TCPConnection(); 9 | /* 10 | */ 11 | void ActiveOpen(); 12 | void PassiveOpen(); 13 | void Close(); 14 | /* 15 | */ 16 | void Send(); 17 | void Acknowledge(); 18 | void Synchronize(); 19 | /* 20 | */ 21 | void ProcessOctet(TCPOctetStream*); 22 | private: 23 | friend class TCPState; 24 | void ChangeState(TCPState*); 25 | private: 26 | TCPState* _state; 27 | }; 28 | /* 29 | */ 30 | class TCPState { 31 | public: 32 | virtual void Transmit(TCPConnection*, TCPOctetStream*); 33 | virtual void ActiveOpen(TCPConnection*); 34 | virtual void PassiveOpen(TCPConnection*); 35 | virtual void Close(TCPConnection*); 36 | virtual void Synchronize(TCPConnection*); 37 | virtual void Acknowledge(TCPConnection*); 38 | virtual void Send(TCPConnection*); 39 | protected: 40 | void ChangeState(TCPConnection*, TCPState*); 41 | }; 42 | 43 | class TCPClosed : public TCPState { 44 | public: 45 | static TCPState* Instance(); 46 | 47 | virtual void ActiveOpen(TCPConnection*); 48 | virtual void PassiveOpen(TCPConnection*); 49 | // ... 50 | }; 51 | /* 52 | */ 53 | /* 54 | */ 55 | TCPConnection::TCPConnection () { 56 | _state = TCPClosed::Instance(); 57 | } 58 | /* 59 | */ 60 | void TCPConnection::ChangeState (TCPState* s) { 61 | _state = s; 62 | } 63 | /* 64 | */ 65 | void TCPConnection::ActiveOpen () { 66 | _state->ActiveOpen(this); 67 | } 68 | /* 69 | */ 70 | void TCPConnection::PassiveOpen () { 71 | _state->PassiveOpen(this); 72 | } 73 | /* 74 | */ 75 | void TCPConnection::Close () { 76 | _state->Close(this); 77 | } 78 | /* 79 | */ 80 | void TCPConnection::Acknowledge () { 81 | _state->Acknowledge(this); 82 | } 83 | /* 84 | */ 85 | void TCPConnection::Synchronize () { 86 | _state->Synchronize(this); 87 | } 88 | /* 89 | */ 90 | void TCPState::Transmit (TCPConnection*, TCPOctetStream*) { } 91 | void TCPState::ActiveOpen (TCPConnection*) { } 92 | void TCPState::PassiveOpen (TCPConnection*) { } 93 | void TCPState::Close (TCPConnection*) { } 94 | void TCPState::Synchronize (TCPConnection*) { } 95 | /* 96 | */ 97 | void TCPState::ChangeState (TCPConnection* t, TCPState* s) { 98 | t->ChangeState(s); 99 | } 100 | /* 101 | */ 102 | class TCPEstablished : public TCPState { 103 | public: 104 | static TCPState* Instance(); 105 | 106 | virtual void Transmit(TCPConnection*, TCPOctetStream*); 107 | virtual void Close(TCPConnection*); 108 | }; 109 | /* 110 | */ 111 | class TCPListen : public TCPState { 112 | public: 113 | static TCPState* Instance(); 114 | 115 | virtual void Send(TCPConnection*); 116 | // ... 117 | }; 118 | /* 119 | */ 120 | void TCPClosed::ActiveOpen (TCPConnection* t) { 121 | // send SYN, receive SYN, ACK, etc. 122 | 123 | ChangeState(t, TCPEstablished::Instance()); 124 | } 125 | /* 126 | */ 127 | void TCPClosed::PassiveOpen (TCPConnection* t) { 128 | ChangeState(t, TCPListen::Instance()); 129 | } 130 | /* 131 | */ 132 | void TCPEstablished::Close (TCPConnection* t) { 133 | // send FIN, receive ACK of FIN 134 | 135 | ChangeState(t, TCPListen::Instance()); 136 | } 137 | /* 138 | */ 139 | void TCPEstablished::Transmit ( 140 | TCPConnection* t, TCPOctetStream* o 141 | ) { 142 | t->ProcessOctet(o); 143 | } 144 | /* 145 | */ 146 | void TCPListen::Send (TCPConnection* t) { 147 | // send SYN, receive SYN, ACK, etc. 148 | 149 | ChangeState(t, TCPEstablished::Instance()); 150 | } 151 | /* 152 | */ 153 | -------------------------------------------------------------------------------- /C++/memento.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | */ 3 | class Memento; 4 | /* 5 | */ 6 | class State; 7 | 8 | class Originator { 9 | public: 10 | Memento* CreateMemento(); 11 | void SetMemento(const Memento*); 12 | // ... 13 | private: 14 | State* _state; // internal data structures 15 | // ... 16 | }; 17 | /* 18 | */ 19 | class Memento { 20 | public: 21 | // narrow public interface 22 | virtual ~Memento(); 23 | private: 24 | // private members accessible only to Originator 25 | friend class Originator; 26 | Memento(); 27 | /* 28 | */ 29 | void SetState(State*); 30 | State* GetState(); 31 | // ... 32 | private: 33 | State* _state; 34 | // ... 35 | }; 36 | /* 37 | */ 38 | #include "Geom.h" 39 | class ConstraintSolverMemento; 40 | class ConstraintSolver; 41 | 42 | class Graphic { 43 | public: 44 | void Move(const Point&); 45 | }; 46 | 47 | /* 48 | */ 49 | class Graphic; 50 | // base class for graphical objects in the graphical editor 51 | 52 | class MoveCommand { 53 | public: 54 | MoveCommand(Graphic* target, const Point& delta); 55 | void Execute(); 56 | void Unexecute(); 57 | private: 58 | ConstraintSolverMemento* _state; 59 | Point _delta; 60 | Graphic* _target; 61 | }; 62 | /* 63 | */ 64 | class ConstraintSolver { 65 | public: 66 | static ConstraintSolver* Instance(); 67 | /* 68 | */ 69 | void Solve(); 70 | void AddConstraint( 71 | Graphic* startConnection, Graphic* endConnection 72 | ); 73 | void RemoveConstraint( 74 | Graphic* startConnection, Graphic* endConnection 75 | ); 76 | /* 77 | */ 78 | ConstraintSolverMemento* CreateMemento(); 79 | void SetMemento(ConstraintSolverMemento*); 80 | private: 81 | // nontrivial state and operations for enforcing 82 | // connectivity semantics 83 | }; 84 | /* 85 | */ 86 | class ConstraintSolverMemento { 87 | public: 88 | virtual ~ConstraintSolverMemento(); 89 | private: 90 | friend class ConstraintSolver; 91 | ConstraintSolverMemento(); 92 | 93 | // private constraint solver state 94 | }; 95 | /* 96 | */ 97 | void MoveCommand::Execute () { 98 | ConstraintSolver* solver = ConstraintSolver::Instance(); 99 | _state = solver->CreateMemento(); // create a memento 100 | _target->Move(_delta); 101 | solver->Solve(); 102 | } 103 | /* 104 | */ 105 | void MoveCommand::Unexecute () { 106 | ConstraintSolver* solver = ConstraintSolver::Instance(); 107 | _target->Move(-_delta); 108 | solver->SetMemento(_state); // restore solver state 109 | solver->Solve(); 110 | } 111 | /* 112 | */ 113 | class IterationState; 114 | /* 115 | */ 116 | template 117 | class Collection { 118 | public: 119 | Collection(); 120 | 121 | IterationState* CreateInitialState(); 122 | void Next(IterationState*); 123 | bool IsDone(const IterationState*) const; 124 | Item CurrentItem(const IterationState*) const; 125 | IterationState* Copy(const IterationState*) const; 126 | 127 | void Append(const Item&); 128 | void Remove(const Item&); 129 | // ... 130 | }; 131 | /* 132 | */ 133 | class ItemType { 134 | public: 135 | void Process(); 136 | // ... 137 | }; 138 | /* 139 | */ 140 | class IterationState { 141 | }; 142 | void dummy () { 143 | /* 144 | */ 145 | Collection aCollection; 146 | IterationState* state; 147 | 148 | state = aCollection.CreateInitialState(); 149 | 150 | while (!aCollection.IsDone(state)) { 151 | aCollection.CurrentItem(state)->Process(); 152 | aCollection.Next(state); 153 | } 154 | delete state; 155 | /* 156 | */ 157 | } 158 | /* 159 | */ 160 | -------------------------------------------------------------------------------- /Java/src/designpatterns/Mediator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | /** 12 | * 13 | * @author jtherrell 14 | */ 15 | interface Mediator { 16 | public void widgetChanged(Widget changedWidget); 17 | } 18 | 19 | class FontDialogMediator implements Mediator { 20 | private Button ok; 21 | private Button cancel; 22 | private ListBox fontList; 23 | private EntryField fontName; 24 | private Log log; 25 | 26 | public FontDialogMediator(Log log) { 27 | ok = new Button(this, "OK", log); 28 | cancel = new Button(this, "CANCEL", log); 29 | fontList = new ListBox(this, log); 30 | List fonts = new ArrayList(); 31 | fonts.add("Helvetica"); 32 | fonts.add("Myriad Pro"); 33 | fonts.add("Times New Roman"); 34 | fontList.setList(fonts); 35 | fontName = new EntryField(this, log); 36 | this.log = log; 37 | } 38 | 39 | @Override 40 | public void widgetChanged(Widget changedWidget) { 41 | if (changedWidget == fontList) { 42 | log.append("updating fontName field "); 43 | fontName.setText(fontList.getSelection()); 44 | } else if (changedWidget == ok) { 45 | log.append("OK "); 46 | } else if (changedWidget == cancel) { 47 | log.append("CANCEL "); 48 | } 49 | } 50 | 51 | public Widget[] getWidgets() { 52 | Widget[] widgets = {ok, cancel, fontList, fontName}; 53 | return widgets; 54 | } 55 | 56 | } 57 | 58 | abstract class Widget { 59 | private Mediator mediator; 60 | protected Log log; 61 | 62 | public void changed() { 63 | mediator.widgetChanged(this); 64 | } 65 | abstract public void handleMouse(MouseEvent e); 66 | public Widget(Mediator mediator, Log log) { 67 | this.mediator = mediator; 68 | this.log = log; 69 | } 70 | } 71 | 72 | class ListBox extends Widget { 73 | private List listItems; 74 | private int currentSelectionIndex; 75 | 76 | public ListBox(Mediator mediator, Log log) { 77 | super(mediator, log); 78 | listItems = new ArrayList(); 79 | currentSelectionIndex = 0; 80 | } 81 | 82 | @Override 83 | public void handleMouse(MouseEvent e) { 84 | log.append("ListBox changed "); 85 | //pretend the selected item in the list changed 86 | changed(); 87 | } 88 | 89 | public String getSelection() { 90 | return listItems.get(currentSelectionIndex); 91 | } 92 | 93 | public void setList(List listItems) { 94 | this.listItems = listItems; 95 | } 96 | } 97 | 98 | class EntryField extends Widget { 99 | private String entryText; 100 | 101 | public EntryField(Mediator mediator, Log log) { 102 | super(mediator, log); 103 | entryText = ""; 104 | } 105 | 106 | public String getText() { 107 | return entryText; 108 | } 109 | 110 | public void setText(String text) { 111 | entryText = text; 112 | } 113 | 114 | @Override 115 | public void handleMouse(MouseEvent e) { 116 | log.append("EntryField changed "); 117 | //pretend the selected item in the list changed 118 | changed(); 119 | } 120 | } 121 | 122 | class Button extends Widget { 123 | private String buttonLabel; 124 | 125 | public Button(Mediator mediator, String label, Log log) { 126 | super(mediator, log); 127 | buttonLabel = label; 128 | } 129 | 130 | public void setLabel(String label) { 131 | buttonLabel = label; 132 | } 133 | 134 | @Override 135 | public void handleMouse(MouseEvent e) { 136 | log.append("Button changed "); 137 | //pretend the button was clicked 138 | changed(); 139 | } 140 | 141 | } 142 | 143 | class MouseEvent{} -------------------------------------------------------------------------------- /C++/Foundation.h: -------------------------------------------------------------------------------- 1 | /* 2 | */ 3 | #ifndef Foundation_H 4 | #define Foundation_H 5 | /* 6 | */ 7 | class ostream; 8 | const long DEFAULT_LIST_CAPACITY = 200; 9 | #ifndef defs_h 10 | #define defs_h 11 | /* 12 | */ 13 | //typedef int bool; 14 | //const int true = 1; 15 | //const int false = 0; 16 | /* 17 | */ 18 | #endif 19 | /* 20 | */ 21 | template 22 | class List { 23 | public: 24 | List(long size = DEFAULT_LIST_CAPACITY); 25 | List(List&); 26 | ~List(); 27 | List& operator=(const List&); 28 | /* 29 | */ 30 | long Count() const; 31 | Item& Get(long index) const; 32 | Item& First() const; 33 | Item& Last() const; 34 | bool Includes(const Item&) const; 35 | /* 36 | */ 37 | void Append(const Item&); 38 | void Prepend(const Item&); 39 | /* 40 | */ 41 | void Remove(const Item&); 42 | void RemoveLast(); 43 | void RemoveFirst(); 44 | void RemoveAll(); 45 | /* 46 | */ 47 | Item& Top() const; 48 | void Push(const Item&); 49 | Item& Pop(); 50 | }; 51 | /* 52 | */ 53 | template 54 | class Iterator { 55 | public: 56 | virtual void First() = 0; 57 | virtual void Next() = 0; 58 | virtual bool IsDone() const = 0; 59 | virtual Item CurrentItem() const = 0; 60 | protected: 61 | Iterator(); 62 | }; 63 | /* 64 | */ 65 | template 66 | class ListIterator : public Iterator { 67 | public: 68 | ListIterator(const List* aList); 69 | /* 70 | */ 71 | virtual void First(); 72 | virtual void Next(); 73 | virtual bool IsDone() const; 74 | virtual Item CurrentItem() const; 75 | }; 76 | /* 77 | */ 78 | typedef float Coord; 79 | /* 80 | */ 81 | class ostream; 82 | class istream; 83 | /* 84 | */ 85 | class Point { 86 | public: 87 | static const Point& Zero; 88 | /* 89 | */ 90 | Point(Coord x = 0.0, Coord y = 0.0); 91 | /* 92 | */ 93 | Coord X() const; void X(Coord x); 94 | Coord Y() const; void Y(Coord y); 95 | /* 96 | */ 97 | friend Point& operator+(const Point&, const Point&); 98 | friend Point& operator-(const Point&, const Point&); 99 | friend Point& operator*(const Point&, const Point&); 100 | friend Point& operator/(const Point&, const Point&); 101 | /* 102 | */ 103 | Point& operator+=(const Point&); 104 | Point& operator-=(const Point&); 105 | Point& operator*=(const Point&); 106 | Point& operator/=(const Point&); 107 | /* 108 | */ 109 | Point operator-(); 110 | /* 111 | */ 112 | friend bool operator==(const Point&, const Point&); 113 | friend bool operator!=(const Point&, const Point&); 114 | /* 115 | */ 116 | friend ostream& operator<<(ostream&, const Point&); 117 | friend istream& operator>>(istream&, Point&); 118 | }; 119 | /* 120 | */ 121 | class Rect { 122 | public: 123 | static const Rect& Zero; 124 | /* 125 | */ 126 | Rect(Coord x, Coord y, Coord w, Coord h); 127 | Rect(const Point& origin, const Point& extent); 128 | /* 129 | */ 130 | Coord Width() const; void Width(Coord); 131 | Coord Height() const; void Height(Coord); 132 | Coord Left() const; void Left(Coord); 133 | Coord Bottom() const; void Bottom(Coord); 134 | /* 135 | */ 136 | Point& Origin() const; void Origin(const Point&); 137 | Point& Extent() const; void Extent(const Point&); 138 | /* 139 | */ 140 | void MoveTo(const Point&); 141 | void MoveBy(const Point&); 142 | /* 143 | */ 144 | bool IsEmpty() const; 145 | bool Contains(const Point&) const; 146 | }; 147 | /* 148 | */ 149 | void dummy_found () { 150 | Rect* tmp = new 151 | /* 152 | */ 153 | Rect(Point(0, 0), Point(0, 0)); 154 | /* 155 | */ 156 | } 157 | #endif 158 | /* 159 | */ 160 | -------------------------------------------------------------------------------- /Java/src/designpatterns/Interpreter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import java.util.Map; 9 | import java.util.HashMap; 10 | 11 | /** 12 | * 13 | * @author jtherrell 14 | */ 15 | interface BooleanExp { 16 | public boolean evaluate(Context context); 17 | public BooleanExp replace(String string, BooleanExp exp); 18 | public BooleanExp copy(); 19 | } 20 | 21 | class Context { 22 | private Map contextMap; 23 | 24 | public Context() { 25 | contextMap = new HashMap(); 26 | contextMap.put(true, true); 27 | contextMap.put(false, false); 28 | } 29 | 30 | public boolean lookup(Object obj) { 31 | return contextMap.get(obj); 32 | } 33 | public void assign(VariableExp exp, boolean bool) { 34 | contextMap.put(exp.name(), bool); 35 | } 36 | } 37 | 38 | class VariableExp implements BooleanExp { 39 | private String name; 40 | 41 | public VariableExp(String name) { 42 | this.name = name; 43 | } 44 | 45 | public String name() { 46 | return name; 47 | } 48 | 49 | public boolean evaluate(Context context) { 50 | return context.lookup(name); 51 | } 52 | 53 | public BooleanExp replace(String name, BooleanExp exp) { 54 | if (this.name.equals(name)) 55 | return exp.copy(); 56 | else 57 | return copy(); 58 | } 59 | 60 | public BooleanExp copy() { 61 | return new VariableExp(name); 62 | } 63 | } 64 | 65 | class Constant implements BooleanExp { 66 | Boolean bool; 67 | 68 | public Constant(Boolean bool) { 69 | this.bool = bool; 70 | } 71 | 72 | public boolean evaluate(Context context) { 73 | return context.lookup(bool); 74 | } 75 | 76 | public BooleanExp replace(String string, BooleanExp exp) { 77 | return this; 78 | } 79 | 80 | public BooleanExp copy() { 81 | return new Constant(bool); 82 | } 83 | } 84 | 85 | class AndExp implements BooleanExp { 86 | private BooleanExp operand1, operand2; 87 | 88 | public AndExp(BooleanExp operand1, BooleanExp operand2) { 89 | this.operand1 = operand1; 90 | this.operand2 = operand2; 91 | } 92 | 93 | public boolean evaluate(Context context) { 94 | return operand1.evaluate(context) && operand2.evaluate(context); 95 | } 96 | 97 | public BooleanExp replace(String name, BooleanExp exp) { 98 | return new AndExp(operand1.replace(name, exp), 99 | operand2.replace(name, exp)); 100 | } 101 | 102 | public BooleanExp copy() { 103 | return new AndExp(operand1.copy(), operand2.copy()); 104 | } 105 | } 106 | 107 | class OrExp implements BooleanExp { 108 | private BooleanExp operand1, operand2; 109 | 110 | public OrExp(BooleanExp operand1, BooleanExp operand2) { 111 | this.operand1 = operand1; 112 | this.operand2 = operand2; 113 | } 114 | 115 | public boolean evaluate(Context context) { 116 | return operand1.evaluate(context) || operand2.evaluate(context); 117 | } 118 | 119 | public BooleanExp replace(String name, BooleanExp exp) { 120 | return new OrExp(operand1.replace(name, exp), 121 | operand2.replace(name, exp)); 122 | } 123 | 124 | public BooleanExp copy() { 125 | return new OrExp(operand1.copy(), operand2.copy()); 126 | } 127 | 128 | } 129 | 130 | class NotExp implements BooleanExp { 131 | private BooleanExp exp; 132 | 133 | public NotExp(BooleanExp exp) { 134 | this.exp = exp; 135 | } 136 | 137 | public boolean evaluate(Context context) { 138 | return !exp.evaluate(context); 139 | } 140 | 141 | public BooleanExp replace(String name, BooleanExp exp) { 142 | return new NotExp(exp.replace(name, exp)); 143 | } 144 | 145 | public BooleanExp copy() { 146 | return new NotExp(exp.copy()); 147 | } 148 | } -------------------------------------------------------------------------------- /Java/src/designpatterns/Visitor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this template, choose Tools | Templates 3 | * and open the template in the editor. 4 | */ 5 | 6 | package designpatterns; 7 | 8 | import java.util.List; 9 | import java.util.ListIterator; 10 | 11 | /** 12 | * 13 | * @author jtherrell 14 | */ 15 | abstract class Equipment { 16 | 17 | private String name; 18 | private double price; 19 | 20 | public Equipment(String name, double price) { 21 | this.name = name; 22 | this.price = price; 23 | } 24 | 25 | public String name() { return name; } 26 | public double price() { return price; } 27 | abstract public void accept(EquipmentVisitor visitor); 28 | } 29 | 30 | abstract class CompositeEquipment extends Equipment { 31 | protected List parts; 32 | 33 | public CompositeEquipment(String name, double price, List parts) { 34 | super(name, price); 35 | this.parts = parts; 36 | } 37 | 38 | abstract public void accept(EquipmentVisitor visitor); 39 | } 40 | 41 | class FloppyDisk extends Equipment { 42 | 43 | public FloppyDisk(String name, double price) { 44 | super(name, price); 45 | } 46 | 47 | public void accept(EquipmentVisitor visitor) { 48 | visitor.visitFloppyDisk(this); 49 | } 50 | } 51 | class Card extends Equipment{ 52 | 53 | public Card(String name, double price) { 54 | super(name, price); 55 | } 56 | 57 | public void accept(EquipmentVisitor visitor) { 58 | visitor.visitCard(this); 59 | } 60 | } 61 | 62 | class Bus extends CompositeEquipment{ 63 | 64 | public Bus(String name, double price, List parts) { 65 | super(name, price, parts); 66 | } 67 | 68 | @Override 69 | public void accept(EquipmentVisitor visitor) { 70 | ListIterator iter = parts.listIterator(); 71 | Equipment e; 72 | while(iter.hasNext()) { 73 | e = iter.next(); 74 | e.accept(visitor); 75 | } 76 | visitor.visitBus(this); 77 | } 78 | } 79 | 80 | class Chassis extends CompositeEquipment { 81 | 82 | public Chassis(String name, double price, List parts) { 83 | super(name, price, parts); 84 | } 85 | 86 | @Override 87 | public void accept(EquipmentVisitor visitor) { 88 | ListIterator iter = parts.listIterator(); 89 | Equipment e; 90 | while(iter.hasNext()) { 91 | e = iter.next(); 92 | e.accept(visitor); 93 | } 94 | visitor.visitChassis(this); 95 | } 96 | 97 | } 98 | 99 | interface EquipmentVisitor{ 100 | 101 | public void visitFloppyDisk(FloppyDisk floppy); 102 | public void visitCard(Card card); 103 | public void visitChassis(Chassis chassis); 104 | public void visitBus(Bus bus); 105 | } 106 | 107 | class PricingVisitor implements EquipmentVisitor { 108 | 109 | private double total; 110 | 111 | public double total() { 112 | return total; 113 | } 114 | 115 | public void visitFloppyDisk(FloppyDisk floppy) { 116 | total += floppy.price(); 117 | } 118 | 119 | public void visitCard(Card card) { 120 | total += card.price(); 121 | } 122 | 123 | public void visitChassis(Chassis chassis) { 124 | total += chassis.price(); 125 | } 126 | 127 | public void visitBus(Bus bus) { 128 | total += bus.price(); 129 | } 130 | } 131 | 132 | class InventoryVisitor implements EquipmentVisitor { 133 | 134 | private List inventory; 135 | 136 | public InventoryVisitor(List inventory) { 137 | this.inventory = inventory; 138 | } 139 | 140 | public void visitFloppyDisk(FloppyDisk floppy) { 141 | inventory.add(floppy); 142 | } 143 | 144 | public void visitCard(Card card) { 145 | inventory.add(card); 146 | } 147 | 148 | public void visitChassis(Chassis chassis) { 149 | inventory.add(chassis); 150 | } 151 | 152 | public void visitBus(Bus bus) { 153 | inventory.add(bus); 154 | } 155 | } -------------------------------------------------------------------------------- /C++/composite.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | /* 3 | */ 4 | class Composite; 5 | 6 | class Component { 7 | public: 8 | //... 9 | virtual Composite* GetComposite() { return 0; } 10 | }; 11 | /* 12 | */ 13 | class Composite : public Component { 14 | public: 15 | void Add(Component*); 16 | // ... 17 | virtual Composite* GetComposite() { return this; } 18 | }; 19 | /* 20 | */ 21 | class Leaf : public Component { 22 | // ... 23 | }; 24 | /* 25 | */ 26 | void dummy () { 27 | /* 28 | */ 29 | Composite* aComposite = new Composite; 30 | Leaf* aLeaf = new Leaf; 31 | 32 | Component* aComponent; 33 | Composite* test; 34 | /* 35 | */ 36 | aComponent = aComposite; 37 | if (test = aComponent->GetComposite()) { 38 | test->Add(new Leaf); 39 | } 40 | /* 41 | */ 42 | aComponent = aLeaf; 43 | 44 | if (test = aComponent->GetComposite()) { 45 | test->Add(new Leaf); // will not add leaf 46 | } 47 | /* 48 | */ 49 | } 50 | /* 51 | */ 52 | #include "List.h" 53 | #include 54 | typedef int Watt; 55 | typedef int Currency; 56 | typedef int Power; 57 | /* 58 | */ 59 | class Equipment { 60 | public: 61 | virtual ~Equipment(); 62 | 63 | const char* Name() { return _name; } 64 | /* 65 | */ 66 | virtual Watt Power(); 67 | virtual Currency NetPrice(); 68 | virtual Currency DiscountPrice(); 69 | /* 70 | */ 71 | virtual void Add(Equipment*); 72 | virtual void Remove(Equipment*); 73 | virtual Iterator* CreateIterator(); 74 | protected: 75 | Equipment(const char*); 76 | private: 77 | const char* _name; 78 | }; 79 | /* 80 | */ 81 | class FloppyDisk : public Equipment { 82 | public: 83 | FloppyDisk(const char*); 84 | virtual ~FloppyDisk(); 85 | /* 86 | */ 87 | virtual Watt Power(); 88 | virtual Currency NetPrice(); 89 | virtual Currency DiscountPrice(); 90 | }; 91 | /* 92 | */ 93 | class CompositeEquipment : public Equipment { 94 | public: 95 | virtual ~CompositeEquipment(); 96 | /* 97 | */ 98 | virtual Watt Power(); 99 | virtual Currency NetPrice(); 100 | virtual Currency DiscountPrice(); 101 | /* 102 | */ 103 | virtual void Add(Equipment*); 104 | virtual void Remove(Equipment*); 105 | virtual Iterator* CreateIterator(); 106 | /* 107 | */ 108 | protected: 109 | CompositeEquipment(const char*); 110 | private: 111 | List _equipment; 112 | }; 113 | /* 114 | */ 115 | Currency CompositeEquipment::NetPrice () { 116 | Iterator* i = CreateIterator(); 117 | Currency total = 0; 118 | 119 | for (i->First(); !i->IsDone(); i->Next()) { 120 | total += i->CurrentItem()->NetPrice(); 121 | } 122 | delete i; 123 | return total; 124 | } 125 | /* 126 | */ 127 | class Chassis : public CompositeEquipment { 128 | public: 129 | Chassis(const char*); 130 | virtual ~Chassis(); 131 | /* 132 | */ 133 | virtual Watt Power(); 134 | virtual Currency NetPrice(); 135 | virtual Currency DiscountPrice(); 136 | }; 137 | /* 138 | */ 139 | class Cabinet : public CompositeEquipment { 140 | public: 141 | Cabinet(const char*); 142 | }; 143 | class Bus : public CompositeEquipment { 144 | public: 145 | Bus(const char*); 146 | }; 147 | class Card : public Equipment { 148 | public: 149 | Card(const char*); 150 | }; 151 | void dummy1 () { 152 | /* 153 | */ 154 | Cabinet* cabinet = new Cabinet("PC Cabinet"); 155 | Chassis* chassis = new Chassis("PC Chassis"); 156 | /* 157 | */ 158 | cabinet->Add(chassis); 159 | /* 160 | */ 161 | Bus* bus = new Bus("MCA Bus"); 162 | bus->Add(new Card("16Mbs Token Ring")); 163 | /* 164 | */ 165 | chassis->Add(bus); 166 | chassis->Add(new FloppyDisk("3.5in Floppy")); 167 | 168 | cout << "The net price is " << chassis->NetPrice() << endl; 169 | /* 170 | */ 171 | } 172 | /* 173 | */ 174 | -------------------------------------------------------------------------------- /C++/builder.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | */ 3 | 4 | #include "MazeParts.h" 5 | #include "MazeGame.h" 6 | #include 7 | using namespace std; 8 | /* 9 | */ 10 | class MazeBuilder { 11 | public: 12 | virtual void BuildMaze() { } 13 | virtual void BuildRoom(int room) { } 14 | virtual void BuildDoor(int roomFrom, int roomTo) { } 15 | 16 | virtual Maze* GetMaze() { return 0; } 17 | protected: 18 | MazeBuilder(); 19 | }; 20 | /* 21 | */ 22 | Maze* MazeGame::CreateMaze (MazeBuilder& builder) { 23 | builder.BuildMaze(); 24 | 25 | builder.BuildRoom(1); 26 | builder.BuildRoom(2); 27 | builder.BuildDoor(1, 2); 28 | 29 | return builder.GetMaze(); 30 | } 31 | /* 32 | */ 33 | Maze* MazeGame::CreateComplexMaze (MazeBuilder& builder) { 34 | builder.BuildRoom(1); 35 | // ... 36 | builder.BuildRoom(1001); 37 | 38 | return builder.GetMaze(); 39 | } 40 | /* 41 | */ 42 | class StandardMazeBuilder : public MazeBuilder { 43 | public: 44 | StandardMazeBuilder(); 45 | /* 46 | */ 47 | virtual void BuildMaze(); 48 | virtual void BuildRoom(int); 49 | virtual void BuildDoor(int, int); 50 | /* 51 | */ 52 | virtual Maze* GetMaze(); 53 | private: 54 | Direction CommonWall(Room*, Room*); 55 | Maze* _currentMaze; 56 | }; 57 | 58 | /* 59 | */ 60 | StandardMazeBuilder::StandardMazeBuilder () { 61 | _currentMaze = 0; 62 | } 63 | /* 64 | */ 65 | void StandardMazeBuilder::BuildMaze () { 66 | _currentMaze = new Maze; 67 | } 68 | /* 69 | */ 70 | Maze *StandardMazeBuilder::GetMaze () { 71 | Maze* maze = _currentMaze; 72 | return maze; 73 | } 74 | /* 75 | */ 76 | void StandardMazeBuilder::BuildRoom (int n) { 77 | if (!_currentMaze->RoomNo(n)) { 78 | Room* room = new Room(n); 79 | _currentMaze->AddRoom(room); 80 | /* 81 | */ 82 | room->SetSide(North, new Wall); 83 | room->SetSide(South, new Wall); 84 | room->SetSide(East, new Wall); 85 | room->SetSide(West, new Wall); 86 | } 87 | } 88 | /* 89 | */ 90 | void StandardMazeBuilder::BuildDoor (int n1, int n2) { 91 | Room* r1 = _currentMaze->RoomNo(n1); 92 | Room* r2 = _currentMaze->RoomNo(n2); 93 | Door* d = new Door(r1, r2); 94 | /* 95 | */ 96 | r1->SetSide(CommonWall(r1,r2), d); 97 | r2->SetSide(CommonWall(r2,r1), d); 98 | } 99 | /* 100 | */ 101 | void dummy() { 102 | /* 103 | */ 104 | Maze* maze; 105 | MazeGame game; 106 | StandardMazeBuilder builder; 107 | 108 | game.CreateMaze(builder); 109 | maze = builder.GetMaze(); 110 | /* 111 | */ 112 | } 113 | /* 114 | */ 115 | class CountingMazeBuilder : public MazeBuilder { 116 | public: 117 | CountingMazeBuilder(); 118 | /* 119 | */ 120 | virtual void BuildMaze(); 121 | virtual void BuildRoom(int); 122 | virtual void BuildDoor(int, int); 123 | virtual void AddWall(int, Direction); 124 | /* 125 | */ 126 | void GetCounts(int&, int&) const; 127 | private: 128 | int _doors; 129 | int _rooms; 130 | }; 131 | /* 132 | */ 133 | CountingMazeBuilder::CountingMazeBuilder () { 134 | _rooms = _doors = 0; 135 | } 136 | /* 137 | */ 138 | void CountingMazeBuilder::BuildRoom (int) { 139 | _rooms++; 140 | } 141 | /* 142 | */ 143 | void CountingMazeBuilder::BuildDoor (int, int) { 144 | _doors++; 145 | } 146 | /* 147 | */ 148 | void CountingMazeBuilder::GetCounts ( 149 | int& rooms, int& doors 150 | ) const { 151 | rooms = _rooms; 152 | doors = _doors; 153 | } 154 | /* 155 | */ 156 | void dummy1() { 157 | /* 158 | */ 159 | int rooms, doors; 160 | MazeGame game; 161 | CountingMazeBuilder builder; 162 | 163 | game.CreateMaze(builder); 164 | builder.GetCounts(rooms, doors); 165 | 166 | cout << "The maze has " 167 | << rooms << " rooms and " 168 | << doors << " doors" << endl; 169 | /* 170 | */ 171 | } 172 | /* 173 | */ 174 | -------------------------------------------------------------------------------- /C++/observer.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | */ 3 | class BaseClassSubject { 4 | public: 5 | void Operation (int newValue); 6 | }; 7 | 8 | class MySubject : public BaseClassSubject { 9 | public: 10 | void Operation (int newValue); 11 | private: 12 | int _myInstVar; 13 | }; 14 | 15 | /* 16 | */ 17 | void MySubject::Operation (int newValue) { 18 | BaseClassSubject::Operation(newValue); 19 | // trigger notification 20 | 21 | _myInstVar += newValue; 22 | // update subclass state (too late!) 23 | } 24 | /* 25 | */ 26 | typedef int TextRange; 27 | class Text { 28 | public: 29 | void Cut(int newValue); 30 | void ReplaceRange(int newValue); 31 | void Notify(); 32 | }; 33 | 34 | /* 35 | */ 36 | void Text::Cut (TextRange r) { 37 | ReplaceRange(r); // redefined in subclasses 38 | Notify(); 39 | } 40 | /* 41 | */ 42 | #include "List.h" 43 | /* 44 | */ 45 | class Subject; 46 | 47 | class Observer { 48 | public: 49 | virtual ~ Observer(); 50 | virtual void Update(Subject* theChangedSubject) = 0; 51 | protected: 52 | Observer(); 53 | }; 54 | /* 55 | */ 56 | class Subject { 57 | public: 58 | virtual ~Subject(); 59 | /* 60 | */ 61 | virtual void Attach(Observer*); 62 | virtual void Detach(Observer*); 63 | virtual void Notify(); 64 | protected: 65 | Subject(); 66 | private: 67 | List *_observers; 68 | }; 69 | /* 70 | */ 71 | void Subject::Attach (Observer* o) { 72 | _observers->Append(o); 73 | } 74 | /* 75 | */ 76 | void Subject::Detach (Observer* o) { 77 | _observers->Remove(o); 78 | } 79 | /* 80 | */ 81 | void Subject::Notify () { 82 | ListIterator i(_observers); 83 | 84 | for (i.First(); !i.IsDone(); i.Next()) { 85 | i.CurrentItem()->Update(this); 86 | } 87 | } 88 | /* 89 | */ 90 | class ClockTimer : public Subject { 91 | public: 92 | ClockTimer(); 93 | /* 94 | */ 95 | virtual int GetHour(); 96 | virtual int GetMinute(); 97 | virtual int GetSecond(); 98 | /* 99 | */ 100 | void Tick(); 101 | }; 102 | /* 103 | */ 104 | void ClockTimer::Tick () { 105 | // update internal time-keeping state 106 | // ... 107 | Notify(); 108 | } 109 | /* 110 | */ 111 | class Widget { 112 | public: 113 | virtual void Draw(); 114 | }; 115 | /* 116 | */ 117 | class DigitalClock: public Widget, public Observer { 118 | public: 119 | DigitalClock(ClockTimer*); 120 | virtual ~DigitalClock(); 121 | /* 122 | */ 123 | virtual void Update(Subject*); 124 | // overrides Observer operation 125 | /* 126 | */ 127 | virtual void Draw(); 128 | // overrides Widget operation; 129 | // defines how to draw the digital clock 130 | private: 131 | ClockTimer* _subject; 132 | }; 133 | /* 134 | */ 135 | DigitalClock::DigitalClock (ClockTimer* s) { 136 | _subject = s; 137 | _subject->Attach(this); 138 | } 139 | 140 | DigitalClock::~DigitalClock () { 141 | _subject->Detach(this); 142 | } 143 | /* 144 | */ 145 | void DigitalClock::Update (Subject* theChangedSubject) { 146 | if (theChangedSubject == _subject) { 147 | Draw(); 148 | } 149 | } 150 | /* 151 | */ 152 | void DigitalClock::Draw () { 153 | // get the new values from the subject 154 | 155 | int hour = _subject->GetHour(); 156 | int minute = _subject->GetMinute(); 157 | // etc. 158 | 159 | // draw the digital clock 160 | } 161 | /* 162 | */ 163 | class AnalogClock : public Widget, public Observer { 164 | public: 165 | AnalogClock(ClockTimer*); 166 | virtual void Update(Subject*); 167 | virtual void Draw(); 168 | // ... 169 | }; 170 | /* 171 | */ 172 | ClockTimer* timer = new ClockTimer; 173 | AnalogClock* analogClock = new AnalogClock(timer); 174 | DigitalClock* digitalClock = new DigitalClock(timer); 175 | /* 176 | */ 177 | -------------------------------------------------------------------------------- /Java/build.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | Builds, tests, and runs the project DesignPatterns. 12 | 13 | 74 | 75 | -------------------------------------------------------------------------------- /C++/factorymeth.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | */ 3 | class Product {}; 4 | 5 | #ifdef Implementation1 6 | class MyProduct : public Product {}; 7 | class YourProduct : public Product {}; 8 | class TheirProduct : public Product {}; 9 | typedef int ProductId; 10 | const int MINE = 1; 11 | const int YOURS = 2; 12 | const int THEIRS = 2; 13 | /* 14 | */ 15 | class Creator { 16 | public: 17 | virtual Product* Create(ProductId); 18 | }; 19 | /* 20 | */ 21 | Product* Creator::Create (ProductId id) { 22 | if (id == MINE) return new MyProduct; 23 | if (id == YOURS) return new YourProduct; 24 | // repeat for remaining products... 25 | 26 | return 0; 27 | } 28 | /* 29 | */ 30 | class MyCreator : public Creator { 31 | public: 32 | virtual Product* Create(ProductId); 33 | }; 34 | /* 35 | */ 36 | Product* MyCreator::Create (ProductId id) { 37 | if (id == YOURS) return new MyProduct; 38 | if (id == MINE) return new YourProduct; 39 | // N.B.: switched YOURS and MINE 40 | 41 | if (id == THEIRS) return new TheirProduct; 42 | 43 | return Creator::Create(id); // called if all others fail 44 | } 45 | /* 46 | */ 47 | #endif 48 | #ifdef Implementation2 49 | /* 50 | */ 51 | class Creator { 52 | public: 53 | Product* GetProduct(); 54 | protected: 55 | virtual Product* CreateProduct(); 56 | private: 57 | Product* _product; 58 | }; 59 | /* 60 | */ 61 | Product* Creator::GetProduct () { 62 | if (_product == 0) { 63 | _product = CreateProduct(); 64 | } 65 | return _product; 66 | } 67 | /* 68 | */ 69 | #endif 70 | #ifdef Implementation3 71 | /* 72 | */ 73 | class Creator { 74 | public: 75 | virtual Product* CreateProduct() = 0; 76 | }; 77 | /* 78 | */ 79 | template 80 | class StandardCreator: public Creator { 81 | public: 82 | virtual Product* CreateProduct(); 83 | }; 84 | /* 85 | */ 86 | template 87 | Product* StandardCreator::CreateProduct () { 88 | return new TheProduct; 89 | } 90 | /* 91 | */ 92 | class MyProduct : public Product { 93 | public: 94 | MyProduct(); 95 | // ... 96 | }; 97 | 98 | StandardCreator myCreator; 99 | /* 100 | */ 101 | #endif 102 | /* 103 | */ 104 | #include "MazeParts.h" 105 | /* 106 | */ 107 | class MazeGame { 108 | public: 109 | Maze* CreateMaze(); 110 | /* 111 | */ 112 | // factory methods: 113 | /* 114 | */ 115 | virtual Maze* MakeMaze() const 116 | { return new Maze; } 117 | virtual Room* MakeRoom(int n) const 118 | { return new Room(n); } 119 | virtual Wall* MakeWall() const 120 | { return new Wall; } 121 | virtual Door* MakeDoor(Room* r1, Room* r2) const 122 | { return new Door(r1, r2); } 123 | }; 124 | /* 125 | */ 126 | Maze* MazeGame::CreateMaze () { 127 | Maze* aMaze = MakeMaze(); 128 | /* 129 | */ 130 | Room* r1 = MakeRoom(1); 131 | Room* r2 = MakeRoom(2); 132 | Door* theDoor = MakeDoor(r1, r2); 133 | /* 134 | */ 135 | aMaze->AddRoom(r1); 136 | aMaze->AddRoom(r2); 137 | /* 138 | */ 139 | r1->SetSide(North, MakeWall()); 140 | r1->SetSide(East, theDoor); 141 | r1->SetSide(South, MakeWall()); 142 | r1->SetSide(West, MakeWall()); 143 | /* 144 | */ 145 | r2->SetSide(North, MakeWall()); 146 | r2->SetSide(East, MakeWall()); 147 | r2->SetSide(South, MakeWall()); 148 | r2->SetSide(West, theDoor); 149 | /* 150 | */ 151 | return aMaze; 152 | } 153 | /* 154 | */ 155 | class BombedMazeGame : public MazeGame { 156 | public: 157 | BombedMazeGame(); 158 | /* 159 | */ 160 | virtual Wall* MakeWall() const 161 | { return new BombedWall; } 162 | /* 163 | */ 164 | virtual Room* MakeRoom(int n) const 165 | { return new RoomWithABomb(n); } 166 | }; 167 | /* 168 | */ 169 | class EnchantedMazeGame : public MazeGame { 170 | public: 171 | EnchantedMazeGame(); 172 | /* 173 | */ 174 | virtual Room* MakeRoom(int n) const 175 | { return new EnchantedRoom(n, CastSpell()); } 176 | /* 177 | */ 178 | virtual Door* MakeDoor(Room* r1, Room* r2) const 179 | { return new DoorNeedingSpell(r1, r2); } 180 | protected: 181 | Spell* CastSpell() const; 182 | }; 183 | /* 184 | */ 185 | -------------------------------------------------------------------------------- /C++/proxy.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | */ 3 | #include "Geom.h" 4 | class Event; 5 | 6 | #ifdef Implementation 7 | class Image { 8 | public: 9 | virtual void Draw(const Point&); 10 | }; 11 | 12 | /* 13 | */ 14 | class Image; 15 | extern Image* LoadAnImageFile(const char*); 16 | // external function 17 | /* 18 | */ 19 | class ImagePtr { 20 | public: 21 | ImagePtr(const char* imageFile); 22 | virtual ~ImagePtr(); 23 | /* 24 | */ 25 | virtual Image* operator->(); 26 | virtual Image& operator*(); 27 | private: 28 | Image* LoadImage(); 29 | private: 30 | Image* _image; 31 | const char* _imageFile; 32 | }; 33 | /* 34 | */ 35 | ImagePtr::ImagePtr (const char* theImageFile) { 36 | _imageFile = theImageFile; 37 | _image = 0; 38 | } 39 | /* 40 | */ 41 | Image* ImagePtr::LoadImage () { 42 | if (_image == 0) { 43 | _image = LoadAnImageFile(_imageFile); 44 | } 45 | return _image; 46 | } 47 | /* 48 | */ 49 | Image* ImagePtr::operator-> () { 50 | return LoadImage(); 51 | } 52 | /* 53 | */ 54 | Image& ImagePtr::operator* () { 55 | return *LoadImage(); 56 | } 57 | /* 58 | */ 59 | void dummy () { 60 | /* 61 | */ 62 | ImagePtr image = ImagePtr("anImageFileName"); 63 | image->Draw(Point(50, 100)); 64 | // (image.operator->())->Draw(Point(50, 100)) 65 | /* 66 | */ 67 | } 68 | /* 69 | */ 70 | #endif 71 | /* 72 | */ 73 | #ifdef SampleCode 74 | #include 75 | #include "strings.h" 76 | /* 77 | */ 78 | class Graphic { 79 | public: 80 | virtual ~Graphic(); 81 | /* 82 | */ 83 | virtual void Draw(const Point& at) = 0; 84 | virtual void HandleMouse(Event& event) = 0; 85 | /* 86 | */ 87 | virtual const Point& GetExtent() = 0; 88 | /* 89 | */ 90 | virtual void Load(istream& from) = 0; 91 | virtual void Save(ostream& to) = 0; 92 | protected: 93 | Graphic(); 94 | }; 95 | /* 96 | */ 97 | class Image : public Graphic { 98 | public: 99 | Image(const char* file); // loads image from a file 100 | virtual ~Image(); 101 | /* 102 | */ 103 | virtual void Draw(const Point& at); 104 | virtual void HandleMouse(Event& event); 105 | /* 106 | */ 107 | virtual const Point& GetExtent(); 108 | /* 109 | */ 110 | virtual void Load(istream& from); 111 | virtual void Save(ostream& to); 112 | private: 113 | // ... 114 | }; 115 | /* 116 | */ 117 | class ImageProxy : public Graphic { 118 | public: 119 | ImageProxy(const char* imageFile); 120 | virtual ~ImageProxy(); 121 | /* 122 | */ 123 | virtual void Draw(const Point& at); 124 | virtual void HandleMouse(Event& event); 125 | /* 126 | */ 127 | virtual const Point& GetExtent(); 128 | /* 129 | */ 130 | virtual void Load(istream& from); 131 | virtual void Save(ostream& to); 132 | protected: 133 | Image* GetImage(); 134 | private: 135 | Image* _image; 136 | Point _extent; 137 | char* _fileName; 138 | }; 139 | /* 140 | */ 141 | ImageProxy::ImageProxy (const char* fileName) { 142 | _fileName = strdup(fileName); 143 | _extent = Point::Zero; // don't know extent yet 144 | _image = 0; 145 | } 146 | 147 | Image* ImageProxy::GetImage() { 148 | if (_image == 0) { 149 | _image = new Image(_fileName); 150 | } 151 | return _image; 152 | } 153 | /* 154 | */ 155 | const Point& ImageProxy::GetExtent () { 156 | if (_extent == Point::Zero) { 157 | _extent = GetImage()->GetExtent(); 158 | } 159 | return _extent; 160 | } 161 | /* 162 | */ 163 | void ImageProxy::Draw (const Point& at) { 164 | GetImage()->Draw(at); 165 | } 166 | /* 167 | */ 168 | void ImageProxy::HandleMouse (Event& event) { 169 | GetImage()->HandleMouse(event); 170 | } 171 | /* 172 | */ 173 | void ImageProxy::Save (ostream& to) { 174 | to << _extent << _fileName; 175 | } 176 | /* 177 | */ 178 | void ImageProxy::Load (istream& from) { 179 | from >> _extent >> _fileName; 180 | } 181 | /* 182 | */ 183 | class TextDocument { 184 | public: 185 | TextDocument(); 186 | 187 | void Insert(Graphic*); 188 | // ... 189 | }; 190 | /* 191 | */ 192 | void dummy () { 193 | /* 194 | */ 195 | TextDocument* text = new TextDocument; 196 | // ... 197 | text->Insert(new ImageProxy("anImageFileName")); 198 | /* 199 | */ 200 | } 201 | /* 202 | */ 203 | #endif 204 | /* 205 | */ 206 | -------------------------------------------------------------------------------- /C++/interpreter.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | */ 3 | #include "defs.h" 4 | #include 5 | class VariableExp; 6 | class Context; 7 | /* 8 | */ 9 | class BooleanExp { 10 | public: 11 | BooleanExp(); 12 | virtual ~BooleanExp(); 13 | /* 14 | */ 15 | virtual bool Evaluate(Context&) = 0; 16 | virtual BooleanExp* Replace(const char*, BooleanExp&) = 0; 17 | virtual BooleanExp* Copy() const = 0; 18 | }; 19 | /* 20 | */ 21 | class Context { 22 | public: 23 | bool Lookup(const char*) const; 24 | void Assign(VariableExp*, bool); 25 | }; 26 | /* 27 | */ 28 | class VariableExp : public BooleanExp { 29 | public: 30 | VariableExp(const char*); 31 | virtual ~VariableExp(); 32 | /* 33 | */ 34 | virtual bool Evaluate(Context&); 35 | virtual BooleanExp* Replace(const char*, BooleanExp&); 36 | virtual BooleanExp* Copy() const; 37 | private: 38 | char* _name; 39 | }; 40 | /* 41 | */ 42 | VariableExp::VariableExp (const char* name) { 43 | _name = strdup(name); 44 | } 45 | /* 46 | */ 47 | bool VariableExp::Evaluate (Context& aContext) { 48 | return aContext.Lookup(_name); 49 | } 50 | /* 51 | */ 52 | BooleanExp* VariableExp::Copy () const { 53 | return new VariableExp(_name); 54 | } 55 | /* 56 | */ 57 | BooleanExp* VariableExp::Replace ( 58 | const char* name, BooleanExp& exp 59 | ) { 60 | if (strcmp(name, _name) != 0) { 61 | return exp.Copy(); 62 | } else { 63 | return new VariableExp(_name); 64 | } 65 | } 66 | /* 67 | */ 68 | class AndExp : public BooleanExp { 69 | public: 70 | AndExp(BooleanExp*, BooleanExp*); 71 | virtual ~ AndExp(); 72 | /* 73 | */ 74 | virtual bool Evaluate(Context&); 75 | virtual BooleanExp* Replace(const char*, BooleanExp&); 76 | virtual BooleanExp* Copy() const; 77 | private: 78 | BooleanExp* _operand1; 79 | BooleanExp* _operand2; 80 | }; 81 | /* 82 | */ 83 | AndExp::AndExp (BooleanExp* op1, BooleanExp* op2) { 84 | _operand1 = op1; 85 | _operand2 = op2; 86 | } 87 | /* 88 | */ 89 | bool AndExp::Evaluate (Context& aContext) { 90 | return 91 | _operand1->Evaluate(aContext) && 92 | _operand2->Evaluate(aContext); 93 | } 94 | /* 95 | */ 96 | BooleanExp* AndExp::Copy () const { 97 | return 98 | new AndExp(_operand1->Copy(), _operand2->Copy()); 99 | } 100 | /* 101 | */ 102 | BooleanExp* AndExp::Replace (const char* name, BooleanExp& exp) { 103 | return 104 | new AndExp( 105 | _operand1->Replace(name, exp), 106 | _operand2->Replace(name, exp) 107 | ); 108 | } 109 | /* 110 | */ 111 | class Constant : public BooleanExp { 112 | public: 113 | Constant(int v) { _value = v; }; 114 | 115 | virtual bool Evaluate(Context&); 116 | virtual BooleanExp* Replace(const char*, BooleanExp&); 117 | virtual BooleanExp* Copy() const; 118 | private: 119 | int _value; 120 | }; 121 | 122 | class OrExp : public BooleanExp { 123 | public: 124 | OrExp(BooleanExp*, BooleanExp*); 125 | virtual ~ OrExp(); 126 | 127 | virtual bool Evaluate(Context&); 128 | virtual BooleanExp* Replace(const char*, BooleanExp&); 129 | virtual BooleanExp* Copy() const; 130 | private: 131 | BooleanExp* _operand1; 132 | BooleanExp* _operand2; 133 | }; 134 | 135 | class NotExp : public BooleanExp { 136 | public: 137 | NotExp(BooleanExp*); 138 | virtual ~ NotExp(); 139 | 140 | virtual bool Evaluate(Context&); 141 | virtual BooleanExp* Replace(const char*, BooleanExp&); 142 | virtual BooleanExp* Copy() const; 143 | private: 144 | BooleanExp* _operand; 145 | }; 146 | //main () { 147 | // 148 | // 149 | ///* 150 | //*/ 151 | //BooleanExp* expression; 152 | //Context context; 153 | // 154 | //VariableExp* x = new VariableExp("X"); 155 | //VariableExp* y = new VariableExp("Y"); 156 | // 157 | //expression = new OrExp( 158 | // new AndExp(new Constant(true), x), 159 | // new AndExp(y, new NotExp(x))); 160 | ///* 161 | //*/ 162 | //context.Assign(x, false); 163 | //context.Assign(y, true); 164 | // 165 | //bool result = expression->Evaluate(context); 166 | ///* 167 | //*/ 168 | //BooleanExp* replacement; 169 | //VariableExp* z = new VariableExp("Z"); 170 | // 171 | //replacement = new NotExp(z); 172 | //expression->Replace("Y", *replacement); 173 | // 174 | //context.Assign(z, true); 175 | // 176 | //result = expression ->Evaluate(context); 177 | ///* 178 | //*/ 179 | //} 180 | /* 181 | */ 182 | -------------------------------------------------------------------------------- /C++/strategy.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | */ 3 | #ifdef Consequences1 4 | /* 5 | */ 6 | class Composition { 7 | public: 8 | void Repair(); 9 | void ComposeWithSimpleCompositor(); 10 | void ComposeWithTeXCompositor(); 11 | int _breakingStrategy; 12 | }; 13 | const int SimpleStrategy = 1; 14 | const int TeXStrategy = 2; 15 | /* 16 | */ 17 | void Composition::Repair () { 18 | switch (_breakingStrategy) { 19 | case SimpleStrategy: 20 | ComposeWithSimpleCompositor(); 21 | break; 22 | case TeXStrategy: 23 | ComposeWithTeXCompositor(); 24 | break; 25 | // ... 26 | } 27 | // merge results with existing composition, if necessary 28 | } 29 | /* 30 | */ 31 | #endif 32 | /* 33 | */ 34 | #ifdef Consequences2 35 | class Compositor { 36 | public: 37 | void Compose(); 38 | }; 39 | class Composition { 40 | public: 41 | void Repair(); 42 | Compositor* _compositor; 43 | }; 44 | /* 45 | */ 46 | void Composition::Repair () { 47 | _compositor->Compose(); 48 | // merge results with existing composition, if necessary 49 | } 50 | /* 51 | */ 52 | #endif 53 | /* 54 | */ 55 | #ifdef Implementation 56 | /* 57 | */ 58 | template 59 | class Context { 60 | void Operation() { theStrategy.DoAlgorithm(); } 61 | // ... 62 | private: 63 | AStrategy theStrategy; 64 | }; 65 | /* 66 | */ 67 | class MyStrategy { 68 | public: 69 | void DoAlgorithm(); 70 | }; 71 | 72 | Context aContext; 73 | /* 74 | */ 75 | #endif 76 | /* 77 | */ 78 | #ifdef SampleCode 79 | #include "Geom.h" 80 | /* 81 | */ 82 | class Compositor; 83 | class Component; 84 | /* 85 | */ 86 | class Composition { 87 | public: 88 | Composition(Compositor*); 89 | void Repair(); 90 | private: 91 | Compositor* _compositor; 92 | Component* _components; // the list of components 93 | int _componentCount; // the number of components 94 | int _lineWidth; // the Composition's line width 95 | int* _lineBreaks; // the position of linebreaks 96 | // in components 97 | int _lineCount; // the number of lines 98 | }; 99 | /* 100 | */ 101 | class Compositor { 102 | public: 103 | virtual int Compose( 104 | Coord natural[], Coord stretch[], Coord shrink[], 105 | int componentCount, int lineWidth, int breaks[] 106 | ) = 0; 107 | protected: 108 | Compositor(); 109 | }; 110 | /* 111 | */ 112 | Coord coords[] = { 113 | 1,2,3 114 | }; 115 | int b[] = { 116 | 1,2,2 117 | }; 118 | /* 119 | */ 120 | void Composition::Repair () { 121 | Coord* natural; 122 | Coord* stretchability; 123 | Coord* shrinkability; 124 | int componentCount; 125 | int* breaks; 126 | 127 | // prepare the arrays with the desired component sizes 128 | // ... 129 | /* 130 | */ 131 | // kills comiler warnings 132 | natural = coords; 133 | stretchability = coords; 134 | shrinkability = coords; 135 | componentCount = 1; 136 | breaks = b; 137 | /* 138 | */ 139 | // determine where the breaks are: 140 | int breakCount; 141 | breakCount = _compositor->Compose( 142 | natural, stretchability, shrinkability, 143 | componentCount, _lineWidth, breaks 144 | ); 145 | /* 146 | */ 147 | // lay out components according to breaks 148 | // ... 149 | } 150 | /* 151 | */ 152 | class SimpleCompositor : public Compositor { 153 | public: 154 | SimpleCompositor(); 155 | 156 | virtual int Compose( 157 | Coord natural[], Coord stretch[], Coord shrink[], 158 | int componentCount, int lineWidth, int breaks[] 159 | ); 160 | // ... 161 | }; 162 | /* 163 | */ 164 | class TeXCompositor : public Compositor { 165 | public: 166 | TeXCompositor(); 167 | 168 | virtual int Compose( 169 | Coord natural[], Coord stretch[], Coord shrink[], 170 | int componentCount, int lineWidth, int breaks[] 171 | ); 172 | // ... 173 | }; 174 | /* 175 | */ 176 | class ArrayCompositor : public Compositor { 177 | public: 178 | ArrayCompositor(int interval); 179 | 180 | virtual int Compose( 181 | Coord natural[], Coord stretch[], Coord shrink[], 182 | int componentCount, int lineWidth, int breaks[] 183 | ); 184 | // ... 185 | }; 186 | /* 187 | */ 188 | Composition* quick = new Composition(new SimpleCompositor); 189 | Composition* slick = new Composition(new TeXCompositor); 190 | Composition* iconic = new Composition(new ArrayCompositor(100)); 191 | /* 192 | */ 193 | #endif 194 | /* 195 | */ 196 | -------------------------------------------------------------------------------- /C++/chain.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | */ 3 | #ifdef Implementation1 4 | /* 5 | */ 6 | class HelpHandler { 7 | public: 8 | HelpHandler(HelpHandler* s) : _successor(s) { } 9 | virtual void HandleHelp(); 10 | private: 11 | HelpHandler* _successor; 12 | }; 13 | /* 14 | */ 15 | void HelpHandler::HandleHelp () { 16 | if (_successor) { 17 | _successor->HandleHelp(); 18 | } 19 | } 20 | /* 21 | */ 22 | class Request { 23 | public: 24 | int GetKind(); 25 | }; 26 | class HelpRequest : public Request { 27 | }; 28 | 29 | class PrintRequest : public Request { 30 | }; 31 | 32 | 33 | class Handler { 34 | public: 35 | virtual void HandleRequest(Request* theRequest); 36 | void HandleHelp(HelpRequest*); 37 | void HandlePrint(PrintRequest*); 38 | }; 39 | 40 | const int Help = 1; 41 | const int Print = 2; 42 | const int Preview = 2; 43 | /* 44 | */ 45 | void Handler::HandleRequest (Request* theRequest) { 46 | switch (theRequest->GetKind()) { 47 | case Help: 48 | // cast argument to appropriate type 49 | HandleHelp((HelpRequest*) theRequest); 50 | break; 51 | /* 52 | */ 53 | case Print: 54 | HandlePrint((PrintRequest*) theRequest); 55 | // ... 56 | break; 57 | /* 58 | */ 59 | default: 60 | // ... 61 | break; 62 | } 63 | } 64 | /* 65 | */ 66 | class ExtendedHandler : public Handler { 67 | public: 68 | virtual void HandleRequest(Request* theRequest); 69 | // ... 70 | }; 71 | /* 72 | */ 73 | void ExtendedHandler::HandleRequest (Request* theRequest) { 74 | switch (theRequest->GetKind()) { 75 | case Preview: 76 | // handle the Preview request 77 | break; 78 | /* 79 | */ 80 | default: 81 | // let Handler handle other requests 82 | Handler::HandleRequest(theRequest); 83 | } 84 | } 85 | /* 86 | */ 87 | #endif 88 | /* 89 | */ 90 | #ifdef SampleCode 91 | #include"defs.h" 92 | class Application; 93 | class Dialog; 94 | class HelpHandler; 95 | /* 96 | */ 97 | typedef int Topic; 98 | const Topic NO_HELP_TOPIC = -1; 99 | 100 | class HelpHandler { 101 | public: 102 | HelpHandler(HelpHandler* = 0, Topic = NO_HELP_TOPIC); 103 | virtual bool HasHelp(); 104 | virtual void SetHandler(HelpHandler*, Topic); 105 | virtual void HandleHelp(); 106 | private: 107 | HelpHandler* _successor; 108 | Topic _topic; 109 | }; 110 | /* 111 | */ 112 | HelpHandler::HelpHandler ( 113 | HelpHandler* h, Topic t 114 | ) : _successor(h), _topic(t) { } 115 | /* 116 | */ 117 | bool HelpHandler::HasHelp () { 118 | return _topic != NO_HELP_TOPIC; 119 | } 120 | /* 121 | */ 122 | void HelpHandler::HandleHelp () { 123 | if (_successor != 0) { 124 | _successor->HandleHelp(); 125 | } 126 | } 127 | /* 128 | */ 129 | class Widget : public HelpHandler { 130 | protected: 131 | Widget(Widget* parent, Topic t = NO_HELP_TOPIC); 132 | private: 133 | Widget* _parent; 134 | }; 135 | /* 136 | */ 137 | Widget::Widget (Widget* w, Topic t) : HelpHandler(w, t) { 138 | _parent = w; 139 | } 140 | /* 141 | */ 142 | class Button : public Widget { 143 | public: 144 | Button(Widget* d, Topic t = NO_HELP_TOPIC); 145 | 146 | virtual void HandleHelp(); 147 | // Widget operations that Button overrides... 148 | }; 149 | /* 150 | */ 151 | Button::Button (Widget* h, Topic t) : Widget(h, t) { } 152 | 153 | void Button::HandleHelp () { 154 | if (HasHelp()) { 155 | // offer help on the button 156 | } else { 157 | HelpHandler::HandleHelp(); 158 | } 159 | } 160 | /* 161 | */ 162 | class Dialog : public Widget { 163 | public: 164 | Dialog(HelpHandler* h, Topic t = NO_HELP_TOPIC); 165 | virtual void HandleHelp(); 166 | 167 | // Widget operations that Dialog overrides... 168 | // ... 169 | }; 170 | /* 171 | */ 172 | Dialog::Dialog (HelpHandler* h, Topic t) : Widget(0) { 173 | SetHandler(h, t); 174 | } 175 | /* 176 | */ 177 | void Dialog::HandleHelp () { 178 | if (HasHelp()) { 179 | // offer help on the dialog 180 | } else { 181 | HelpHandler::HandleHelp(); 182 | } 183 | } 184 | /* 185 | */ 186 | class Application : public HelpHandler { 187 | public: 188 | Application(Topic t) : HelpHandler(0, t) { } 189 | 190 | virtual void HandleHelp(); 191 | // application-specific operations... 192 | }; 193 | /* 194 | */ 195 | void Application::HandleHelp () { 196 | // show a list of help topics 197 | } 198 | /* 199 | */ 200 | void dummy () { 201 | /* 202 | */ 203 | const Topic PRINT_TOPIC = 1; 204 | const Topic PAPER_ORIENTATION_TOPIC = 2; 205 | const Topic APPLICATION_TOPIC = 3; 206 | 207 | Application* application = new Application(APPLICATION_TOPIC); 208 | Dialog* dialog = new Dialog(application, PRINT_TOPIC); 209 | Button* button = new Button(dialog, PAPER_ORIENTATION_TOPIC); 210 | /* 211 | */ 212 | button->HandleHelp(); 213 | /* 214 | */ 215 | } 216 | #endif 217 | /* 218 | */ 219 | -------------------------------------------------------------------------------- /C++/visitor.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | */ 3 | // Compilation Instructions 4 | // #define Implementation | Consequences | SampleCode 5 | #include "Foundation.h" 6 | #include 7 | /* 8 | */ 9 | #ifdef Consequences 10 | /* 11 | */ 12 | #ifndef Foundation_H 13 | /* 14 | */ 15 | template 16 | class Iterator { 17 | // ... 18 | Item CurrentItem() const; 19 | }; 20 | /* 21 | */ 22 | #endif 23 | /* 24 | */ 25 | class MyType; 26 | class YourType; 27 | /* 28 | */ 29 | class Visitor { 30 | public: 31 | // ... 32 | void VisitMyType(MyType*); 33 | void VisitYourType(YourType*); 34 | }; 35 | /* 36 | */ 37 | #endif 38 | /* 39 | */ 40 | #ifdef Implementation 41 | class ElementA; 42 | class ElementB; 43 | /* 44 | */ 45 | class Visitor { 46 | public: 47 | virtual void VisitElementA(ElementA*); 48 | virtual void VisitElementB(ElementB*); 49 | 50 | // and so on for other concrete elements 51 | protected: 52 | Visitor(); 53 | }; 54 | /* 55 | */ 56 | class Element { 57 | public: 58 | virtual ~Element(); 59 | virtual void Accept(Visitor&) = 0; 60 | protected: 61 | Element(); 62 | }; 63 | /* 64 | */ 65 | class ElementA : public Element { 66 | public: 67 | ElementA(); 68 | virtual void Accept(Visitor& v) { v.VisitElementA(this); } 69 | }; 70 | /* 71 | */ 72 | class ElementB : public Element { 73 | public: 74 | ElementB(); 75 | virtual void Accept(Visitor& v) { v.VisitElementB(this); } 76 | }; 77 | /* 78 | */ 79 | class CompositeElement : public Element { 80 | public: 81 | virtual void Accept(Visitor&); 82 | private: 83 | List* _children; 84 | }; 85 | /* 86 | */ 87 | void CompositeElement::Accept (Visitor& v) { 88 | ListIterator i(_children); 89 | 90 | for (i.First(); !i.IsDone(); i.Next()) { 91 | i.CurrentItem()->Accept(v); 92 | } 93 | v.VisitCompositeElement(this); 94 | } 95 | /* 96 | */ 97 | #endif Implementation 98 | /* 99 | */ 100 | #ifdef SampleCode 101 | typedef int Watt; 102 | typedef int Currency; 103 | typedef int Power; 104 | class EquipmentVisitor; 105 | class Equipment; 106 | class Card; 107 | class Bus; 108 | class Chassis; 109 | class FloppyDisk; 110 | class Inventory { 111 | public: 112 | void Accumulate(Equipment*); 113 | }; 114 | /* 115 | */ 116 | class Equipment { 117 | public: 118 | virtual ~Equipment(); 119 | 120 | const char* Name() { return _name; } 121 | /* 122 | */ 123 | virtual Watt Power(); 124 | virtual Currency NetPrice(); 125 | virtual Currency DiscountPrice(); 126 | /* 127 | */ 128 | virtual void Accept(EquipmentVisitor&); 129 | protected: 130 | Equipment(const char*); 131 | private: 132 | const char* _name; 133 | }; 134 | /* 135 | */ 136 | class EquipmentVisitor { 137 | public: 138 | virtual ~EquipmentVisitor(); 139 | 140 | virtual void VisitFloppyDisk(FloppyDisk*); 141 | virtual void VisitCard(Card*); 142 | virtual void VisitChassis(Chassis*); 143 | virtual void VisitBus(Bus*); 144 | 145 | // and so on for other concrete subclasses of Equipment 146 | protected: 147 | EquipmentVisitor(); 148 | }; 149 | /* 150 | */ 151 | class FloppyDisk : public Equipment { 152 | public: 153 | virtual void Accept(EquipmentVisitor&); 154 | }; 155 | /* 156 | */ 157 | void FloppyDisk::Accept (EquipmentVisitor& visitor) { 158 | visitor.VisitFloppyDisk(this); 159 | } 160 | /* 161 | */ 162 | class CompositeEquipment : public Equipment { 163 | public: 164 | virtual void Accept(EquipmentVisitor&); 165 | }; 166 | 167 | class Chassis : public CompositeEquipment { 168 | public: 169 | virtual void Accept(EquipmentVisitor&); 170 | List* _parts; 171 | }; 172 | /* 173 | */ 174 | void Chassis::Accept (EquipmentVisitor& visitor) { 175 | for ( 176 | ListIterator i(_parts); 177 | !i.IsDone(); 178 | i.Next() 179 | ) { 180 | i.CurrentItem()->Accept(visitor); 181 | } 182 | visitor.VisitChassis(this); 183 | } 184 | /* 185 | */ 186 | class PricingVisitor : public EquipmentVisitor { 187 | public: 188 | PricingVisitor(); 189 | 190 | Currency& GetTotalPrice(); 191 | /* 192 | */ 193 | virtual void VisitFloppyDisk(FloppyDisk*); 194 | virtual void VisitCard(Card*); 195 | virtual void VisitChassis(Chassis*); 196 | virtual void VisitBus(Bus*); 197 | // ... 198 | private: 199 | Currency _total; 200 | }; 201 | /* 202 | */ 203 | void PricingVisitor::VisitFloppyDisk (FloppyDisk* e) { 204 | _total += e->NetPrice(); 205 | } 206 | /* 207 | */ 208 | void PricingVisitor::VisitChassis (Chassis* e) { 209 | _total += e->DiscountPrice(); 210 | } 211 | /* 212 | */ 213 | class InventoryVisitor : public EquipmentVisitor { 214 | public: 215 | InventoryVisitor(); 216 | 217 | Inventory& GetInventory(); 218 | /* 219 | */ 220 | virtual void VisitFloppyDisk(FloppyDisk*); 221 | virtual void VisitCard(Card*); 222 | virtual void VisitChassis(Chassis*); 223 | virtual void VisitBus(Bus*); 224 | // ... 225 | /* 226 | */ 227 | private: 228 | Inventory _inventory; 229 | }; 230 | /* 231 | */ 232 | void InventoryVisitor::VisitFloppyDisk (FloppyDisk* e) { 233 | _inventory.Accumulate(e); 234 | } 235 | /* 236 | */ 237 | void InventoryVisitor::VisitChassis (Chassis* e) { 238 | _inventory.Accumulate(e); 239 | } 240 | /* 241 | */ 242 | ostream& operator<<(ostream&, const Inventory&); 243 | void dummy() { 244 | /* 245 | */ 246 | Equipment* component; 247 | InventoryVisitor visitor; 248 | 249 | component->Accept(visitor); 250 | cout << "Inventory " 251 | << component->Name() 252 | << visitor.GetInventory(); 253 | /* 254 | */ 255 | } 256 | /* 257 | */ 258 | #endif 259 | /* 260 | */ 261 | -------------------------------------------------------------------------------- /C++/bridge.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | */ 3 | class Body { 4 | public: 5 | void Ref(); 6 | void Unref(); 7 | int RefCount(); 8 | private: 9 | }; 10 | 11 | class Handle { 12 | public: 13 | Handle& operator=(const Handle& other); 14 | private: 15 | Body* _body; 16 | }; 17 | /* 18 | */ 19 | Handle& Handle::operator= (const Handle& other) { 20 | other._body->Ref(); 21 | _body->Unref(); 22 | 23 | if (_body->RefCount() == 0) { 24 | delete _body; 25 | } 26 | _body = other._body; 27 | 28 | return *this; 29 | } 30 | /* 31 | */ 32 | #include "Geom.h" 33 | #include "math.h" 34 | class Window; 35 | 36 | class View { 37 | public: 38 | void drawOn(Window*); 39 | }; 40 | 41 | class WindowImp; 42 | struct Display; 43 | typedef unsigned int Drawable; 44 | typedef struct XXX { int y; } *GC; 45 | extern void xDrawRectangle( 46 | Display*, 47 | Drawable, 48 | GC, 49 | int, 50 | int, 51 | unsigned int, 52 | unsigned int 53 | ); 54 | 55 | struct PPOINTL { 56 | Coord x; 57 | Coord y; 58 | }; 59 | const int GPI_ERROR = 1; 60 | 61 | typedef int HPS; 62 | int GpiBeginPath(HPS, unsigned long); 63 | int GpiSetCurrentPosition(HPS, PPOINTL*); 64 | int GpiPolyLine(HPS, unsigned long, PPOINTL*); 65 | int GpiEndPath(HPS); 66 | void ReportError(); 67 | void GpiStrokePath(HPS, unsigned long, unsigned long); 68 | class WindowSystemFactory { 69 | public: 70 | static WindowSystemFactory* Instance(); 71 | WindowImp* MakeWindowImp(); 72 | }; 73 | 74 | /* 75 | */ 76 | class Window { 77 | public: 78 | Window(View* contents); 79 | 80 | // requests handled by window 81 | virtual void DrawContents(); 82 | /* 83 | */ 84 | virtual void Open(); 85 | virtual void Close(); 86 | virtual void Iconify(); 87 | virtual void Deiconify(); 88 | /* 89 | */ 90 | // requests forwarded to implementation 91 | virtual void SetOrigin(const Point& at); 92 | virtual void SetExtent(const Point& extent); 93 | virtual void Raise(); 94 | virtual void Lower(); 95 | /* 96 | */ 97 | virtual void DrawLine(const Point&, const Point&); 98 | virtual void DrawRect(const Point&, const Point&); 99 | virtual void DrawPolygon(const Point[], int n); 100 | virtual void DrawText(const char*, const Point&); 101 | /* 102 | */ 103 | protected: 104 | WindowImp* GetWindowImp(); 105 | View* GetView(); 106 | /* 107 | */ 108 | private: 109 | WindowImp* _imp; 110 | View* _contents; // the window's contents 111 | }; 112 | /* 113 | */ 114 | class WindowImp { 115 | public: 116 | virtual void ImpTop() = 0; 117 | virtual void ImpBottom() = 0; 118 | virtual void ImpSetExtent(const Point&) = 0; 119 | virtual void ImpSetOrigin(const Point&) = 0; 120 | /* 121 | */ 122 | virtual void DeviceRect(Coord, Coord, Coord, Coord) = 0; 123 | virtual void DeviceText(const char*, Coord, Coord) = 0; 124 | virtual void DeviceBitmap(const char*, Coord, Coord) = 0; 125 | // lots more functions for drawing on windows... 126 | protected: 127 | WindowImp(); 128 | }; 129 | /* 130 | */ 131 | class ApplicationWindow : public Window { 132 | public: 133 | // ... 134 | virtual void DrawContents(); 135 | }; 136 | 137 | void ApplicationWindow::DrawContents () { 138 | GetView()->drawOn(this); 139 | } 140 | /* 141 | */ 142 | class IconWindow : public Window { 143 | public: 144 | // ... 145 | virtual void DrawContents(); 146 | private: 147 | const char* _bitmapName; 148 | }; 149 | /* 150 | */ 151 | void IconWindow::DrawContents() { 152 | WindowImp* imp = GetWindowImp(); 153 | if (imp != 0) { 154 | imp->DeviceBitmap(_bitmapName, 0.0, 0.0); 155 | } 156 | } 157 | /* 158 | */ 159 | void Window::DrawRect (const Point& p1, const Point& p2) { 160 | WindowImp* imp = GetWindowImp(); 161 | imp->DeviceRect(p1.X(), p1.Y(), p2.X(), p2.Y()); 162 | } 163 | /* 164 | */ 165 | class XWindowImp : public WindowImp { 166 | public: 167 | XWindowImp(); 168 | 169 | virtual void DeviceRect(Coord, Coord, Coord, Coord); 170 | // remainder of public interface... 171 | private: 172 | // lots of X window system-specific state, including: 173 | Display* _dpy; 174 | Drawable _winid; // window id 175 | GC _gc; // window graphic context 176 | }; 177 | /* 178 | */ 179 | class PMWindowImp : public WindowImp { 180 | public: 181 | PMWindowImp(); 182 | virtual void DeviceRect(Coord, Coord, Coord, Coord); 183 | 184 | // remainder of public interface... 185 | private: 186 | // lots of PM window system-specific state, including: 187 | HPS _hps; 188 | }; 189 | /* 190 | */ 191 | void XWindowImp::DeviceRect ( 192 | Coord x0, Coord y0, Coord x1, Coord y1 193 | ) { 194 | int x = round(min(x0, x1)); 195 | int y = round(min(y0, y1)); 196 | int w = round(abs(x0 - x1)); 197 | int h = round(abs(y0 - y1)); 198 | xDrawRectangle(_dpy, _winid, _gc, x, y, w, h); 199 | } 200 | /* 201 | */ 202 | void PMWindowImp::DeviceRect ( 203 | Coord x0, Coord y0, Coord x1, Coord y1 204 | ) { 205 | Coord left = min(x0, x1); 206 | Coord right = max(x0, x1); 207 | Coord bottom = min(y0, y1); 208 | Coord top = max(y0, y1); 209 | /* 210 | */ 211 | PPOINTL point[4]; 212 | /* 213 | */ 214 | point[0].x = left; point[0].y = top; 215 | point[1].x = right; point[1].y = top; 216 | point[2].x = right; point[2].y = bottom; 217 | point[3].x = left; point[3].y = bottom; 218 | /* 219 | */ 220 | if ( 221 | (GpiBeginPath(_hps, 1L) == false) || 222 | (GpiSetCurrentPosition(_hps, &point[3]) == false) || 223 | (GpiPolyLine(_hps, 4L, point) == GPI_ERROR) || 224 | (GpiEndPath(_hps) == false) 225 | ) { 226 | // report error 227 | /* 228 | */ 229 | } else { 230 | GpiStrokePath(_hps, 1L, 0L); 231 | } 232 | } 233 | /* 234 | */ 235 | WindowImp* Window::GetWindowImp () { 236 | if (_imp == 0) { 237 | _imp = WindowSystemFactory::Instance()->MakeWindowImp(); 238 | } 239 | return _imp; 240 | } 241 | /* 242 | */ 243 | -------------------------------------------------------------------------------- /C++/iterator.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "defs.h" 3 | using namespace std; 4 | 5 | const int DEFAULT_LIST_CAPACITY = 100; 6 | template class Iterator; 7 | /* 8 | */ 9 | template 10 | class List { 11 | public: 12 | List(long size = DEFAULT_LIST_CAPACITY); 13 | /* 14 | */ 15 | Iterator* CreateIterator() const; 16 | /* 17 | */ 18 | long Count() const; 19 | Item& Get(long index) const; 20 | // ... 21 | }; 22 | /* 23 | */ 24 | template 25 | class Iterator { 26 | public: 27 | virtual void First() = 0; 28 | virtual void Next() = 0; 29 | virtual bool IsDone() const = 0; 30 | virtual Item CurrentItem() const = 0; 31 | protected: 32 | Iterator(); 33 | }; 34 | /* 35 | */ 36 | template 37 | class ListIterator : public Iterator { 38 | public: 39 | ListIterator(const List* aList); 40 | virtual void First(); 41 | virtual void Next(); 42 | virtual bool IsDone() const; 43 | virtual Item CurrentItem() const; 44 | /* 45 | */ 46 | private: 47 | const List* _list; 48 | long _current; 49 | }; 50 | /* 51 | */ 52 | template 53 | ListIterator::ListIterator ( 54 | const List* aList 55 | ) : _list(aList), _current(0) { 56 | } 57 | /* 58 | */ 59 | template 60 | void ListIterator::First () { 61 | _current = 0; 62 | } 63 | /* 64 | */ 65 | template 66 | void ListIterator::Next () { 67 | _current++; 68 | } 69 | /* 70 | */ 71 | template 72 | bool ListIterator::IsDone () const { 73 | return _current >= _list->Count(); 74 | } 75 | /* 76 | */ 77 | class IteratorOutOfBounds : public exception {}; 78 | /* 79 | */ 80 | template 81 | Item ListIterator::CurrentItem () const { 82 | if (IsDone()) { 83 | throw new IteratorOutOfBounds; 84 | } 85 | return _list->Get(_current); 86 | } 87 | /* 88 | */ 89 | template 90 | class ReverseListIterator : public Iterator { 91 | public: 92 | ReverseListIterator(const List* aList); 93 | virtual void First(); 94 | virtual void Next(); 95 | virtual bool IsDone() const; 96 | virtual Item CurrentItem() const; 97 | }; 98 | /* 99 | */ 100 | class Employee { 101 | public: 102 | void Print(); 103 | }; 104 | 105 | /* 106 | */ 107 | void PrintEmployees (Iterator& i) { 108 | for (i.First(); !i.IsDone(); i.Next()) { 109 | i.CurrentItem()->Print(); 110 | } 111 | } 112 | /* 113 | */ 114 | 115 | template 116 | class SkipList : public List { 117 | public: 118 | }; 119 | 120 | template 121 | class SkipListIterator : public ListIterator { 122 | public: 123 | SkipListIterator(const List* aList); 124 | void First(); 125 | void Next(); 126 | bool IsDone() const; 127 | Item CurrentItem() const; 128 | }; 129 | 130 | void dummy () { 131 | /* 132 | */ 133 | List* employees; 134 | // ... 135 | ListIterator forward(employees); 136 | ReverseListIterator backward(employees); 137 | 138 | PrintEmployees(forward); 139 | PrintEmployees(backward); 140 | /* 141 | */ 142 | } 143 | /* 144 | */ 145 | void dummy2 () { 146 | /* 147 | */ 148 | SkipList* employees; 149 | // ... 150 | 151 | SkipListIterator iterator(employees); 152 | PrintEmployees(iterator); 153 | /* 154 | */ 155 | } 156 | /* 157 | */ 158 | template 159 | class AbstractList { 160 | public: 161 | virtual Iterator* CreateIterator() const = 0; 162 | // ... 163 | }; 164 | /* 165 | */ 166 | template 167 | Iterator* List::CreateIterator () const { 168 | return new ListIterator(this); 169 | } 170 | /* 171 | */ 172 | void dummy3() { 173 | /* 174 | */ 175 | // we know only that we have an AbstractList 176 | AbstractList* employees; 177 | // ... 178 | 179 | Iterator* iterator = employees->CreateIterator(); 180 | PrintEmployees(*iterator); 181 | delete iterator; 182 | /* 183 | */ 184 | } 185 | /* 186 | */ 187 | template 188 | class IteratorPtr { 189 | public: 190 | IteratorPtr(Iterator* i): _i(i) { } 191 | ~IteratorPtr() { delete _i; } 192 | /* 193 | */ 194 | Iterator* operator->() { return _i; } 195 | Iterator& operator*() { return *_i; } 196 | private: 197 | // disallow copy and assignment to avoid 198 | // multiple deletions of _i: 199 | 200 | IteratorPtr(const IteratorPtr&); 201 | IteratorPtr& operator=(const IteratorPtr&); 202 | private: 203 | Iterator* _i; 204 | }; 205 | /* 206 | */ 207 | void dummy4 () { 208 | /* 209 | */ 210 | AbstractList* employees; 211 | // ... 212 | 213 | IteratorPtr iterator(employees->CreateIterator()); 214 | PrintEmployees(*iterator); 215 | /* 216 | */ 217 | } 218 | /* 219 | */ 220 | template 221 | class ListTraverser { 222 | public: 223 | ListTraverser(List* aList); 224 | bool Traverse(); 225 | protected: 226 | virtual bool ProcessItem(const Item&) = 0; 227 | private: 228 | ListIterator _iterator; 229 | }; 230 | /* 231 | */ 232 | template 233 | ListTraverser::ListTraverser ( 234 | List* aList 235 | ) : _iterator(aList) { } 236 | /* 237 | */ 238 | template 239 | bool ListTraverser::Traverse () { 240 | bool result = false; 241 | 242 | for ( 243 | _iterator.First(); 244 | !_iterator.IsDone(); 245 | _iterator.Next() 246 | ) { 247 | result = ProcessItem(_iterator.CurrentItem()); 248 | /* 249 | */ 250 | if (result == false) { 251 | break; 252 | } 253 | } 254 | return result; 255 | } 256 | /* 257 | */ 258 | class PrintNEmployees : public ListTraverser { 259 | public: 260 | PrintNEmployees(List* aList, int n) : 261 | ListTraverser(aList), 262 | _total(n), _count(0) { } 263 | /* 264 | */ 265 | protected: 266 | bool ProcessItem(Employee* const&); 267 | private: 268 | int _total; 269 | int _count; 270 | }; 271 | /* 272 | */ 273 | bool PrintNEmployees::ProcessItem (Employee* const& e) { 274 | _count++; 275 | e->Print(); 276 | return _count < _total; 277 | } 278 | /* 279 | */ 280 | void dummy5 () { 281 | /* 282 | */ 283 | List* employees; 284 | // ... 285 | 286 | PrintNEmployees pa(employees, 10); 287 | pa.Traverse(); 288 | /* 289 | */ 290 | ListIterator i(employees); 291 | int count = 0; 292 | /* 293 | */ 294 | for (i.First(); !i.IsDone(); i.Next() ) { 295 | count++; 296 | i.CurrentItem()->Print(); 297 | /* 298 | */ 299 | if (count >= 10) { 300 | break; 301 | } 302 | } 303 | /* 304 | */ 305 | } 306 | /* 307 | */ 308 | template 309 | class FilteringListTraverser { 310 | public: 311 | FilteringListTraverser(List* aList); 312 | bool Traverse(); 313 | protected: 314 | virtual bool ProcessItem(const Item&) = 0; 315 | virtual bool TestItem(const Item&) = 0; 316 | private: 317 | ListIterator _iterator; 318 | }; 319 | /* 320 | */ 321 | template 322 | bool FilteringListTraverser::Traverse () { 323 | bool result = false; 324 | /* 325 | */ 326 | for ( 327 | _iterator.First(); 328 | !_iterator.IsDone(); 329 | _iterator.Next() 330 | ) { 331 | if (TestItem(_iterator.CurrentItem())) { 332 | result = ProcessItem(_iterator.CurrentItem()); 333 | /* 334 | */ 335 | if (result == false) { 336 | break; 337 | } 338 | } 339 | } 340 | return result; 341 | } 342 | /* 343 | */ 344 | -------------------------------------------------------------------------------- /C++/maze.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Geom.h" 3 | #include "MazeParts.h" 4 | 5 | Door::Door (const Door& other) { 6 | _room1 = other._room1; 7 | _room2 = other._room2; 8 | } 9 | 10 | void Door::Initialize (Room* r1, Room* r2) { 11 | _room1 = r1; 12 | _room2 = r2; 13 | } 14 | 15 | Door* Door::Clone () const { 16 | return new Door(*this); 17 | } 18 | 19 | //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 20 | 21 | BombedWall::BombedWall (const BombedWall& other) : Wall(other) { 22 | _bomb = other._bomb; 23 | } 24 | 25 | Wall* BombedWall::Clone () const { 26 | return new BombedWall(*this); 27 | } 28 | 29 | //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 30 | // Factories 31 | #include "MazeFactories.h" 32 | Maze* MazeFactory::MakeMaze() const 33 | { return new Maze; } 34 | Wall* MazeFactory::MakeWall() const 35 | { return new Wall; } 36 | Room* MazeFactory::MakeRoom(int n) const 37 | { return new Room(n); } 38 | Door* MazeFactory::MakeDoor(Room* r1, Room* r2) const 39 | { return new Door(r1, r2); } 40 | 41 | MazeFactory* MazeFactory::_instance = 0; 42 | 43 | #ifdef Singleton 44 | MazeFactory* MazeFactory::Instance () { 45 | if (_instance == 0) { 46 | _instance = new MazeFactory; 47 | } 48 | return _instance; 49 | } 50 | 51 | #else 52 | int strcmp(const char*, const char*); 53 | const char* getenv(const char*); 54 | 55 | MazeFactory* MazeFactory::Instance () { 56 | if (_instance == 0) { 57 | const char* mazeStyle = getenv("MAZESTYLE"); 58 | 59 | if (strcmp(mazeStyle, "bombed") == 0) { 60 | _instance = new BombedMazeFactory; 61 | } else if (strcmp(mazeStyle, "enchanted") == 0) { 62 | _instance = new EnchantedMazeFactory; 63 | 64 | // ... other possible subclasses 65 | 66 | } else { // default 67 | _instance = new MazeFactory; 68 | } 69 | } 70 | return _instance; 71 | } 72 | #endif 73 | 74 | 75 | Wall* BombedMazeFactory::MakeWall () const { 76 | return new BombedWall; 77 | } 78 | Room* BombedMazeFactory::MakeRoom (int n) const { 79 | return new RoomWithABomb(n); 80 | } 81 | 82 | Room* EnchantedMazeFactory::MakeRoom(int n) const 83 | { return new EnchantedRoom(n, CastSpell()); } 84 | Door* EnchantedMazeFactory::MakeDoor(Room* r1, Room* r2) const 85 | { return new DoorNeedingSpell(r1, r2); } 86 | 87 | //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 88 | 89 | class MazePrototypeFactory : public MazeFactory { 90 | public: 91 | MazePrototypeFactory(Maze*, Wall*, Room*, Door*); 92 | 93 | virtual Maze* MakeMaze() const; 94 | virtual Room* MakeRoom(int) const; 95 | virtual Wall* MakeWall() const; 96 | virtual Door* MakeDoor(Room* r1, Room *r2) const; 97 | 98 | private: 99 | Maze* _prototypeMaze; 100 | Room* _prototypeRoom; 101 | Wall* _prototypeWall; 102 | Door* _prototypeDoor; 103 | }; 104 | 105 | MazePrototypeFactory::MazePrototypeFactory (Maze* m, 106 | Wall* w, 107 | Room* r, 108 | Door* d) { 109 | _prototypeMaze = m; 110 | _prototypeWall = w; 111 | _prototypeRoom = r; 112 | _prototypeDoor = d; 113 | } 114 | 115 | Room* MazePrototypeFactory::MakeRoom(int n) const { 116 | Room* room = _prototypeRoom->Clone(); 117 | room->InitializeRoomNo(n); 118 | return room; 119 | } 120 | 121 | Maze* MazePrototypeFactory::MakeMaze() const { 122 | return _prototypeMaze->Clone(); 123 | } 124 | 125 | Wall* MazePrototypeFactory::MakeWall() const { 126 | return _prototypeWall->Clone(); 127 | } 128 | 129 | Door* MazePrototypeFactory::MakeDoor(Room* r1, Room *r2) const { 130 | Door* door = _prototypeDoor->Clone(); 131 | door->Initialize(r1, r2); 132 | return door; 133 | } 134 | 135 | //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 136 | 137 | class MazeBuilder { 138 | public: 139 | virtual void BuildMaze() {}; 140 | virtual void BuildRoom(int) {}; 141 | virtual void BuildDoor(int, int) {}; 142 | 143 | virtual Maze* GetMaze() { return 0; } 144 | // virtual Maze* OrphanMaze() { return 0;} 145 | 146 | protected: 147 | MazeBuilder(); 148 | }; 149 | 150 | //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 151 | 152 | class StandardMazeBuilder : public MazeBuilder { 153 | public: 154 | StandardMazeBuilder(); 155 | 156 | virtual void BuildMaze(); 157 | virtual void BuildRoom(int); 158 | virtual void BuildDoor(int, int); 159 | 160 | virtual Maze* OrphanMaze(); 161 | 162 | private: 163 | Direction CommonWall(Room*, Room*); 164 | Maze* _currentMaze; 165 | }; 166 | 167 | StandardMazeBuilder::StandardMazeBuilder () { 168 | _currentMaze = 0; 169 | } 170 | 171 | void StandardMazeBuilder::BuildMaze () { 172 | _currentMaze = new Maze; 173 | } 174 | 175 | Maze* StandardMazeBuilder::OrphanMaze () { 176 | Maze* maze = _currentMaze; 177 | _currentMaze = 0; 178 | return maze; 179 | } 180 | 181 | void StandardMazeBuilder::BuildRoom (int n) { 182 | if (!_currentMaze->RoomNo(n)) { 183 | Room* room = new Room(n); 184 | _currentMaze->AddRoom(room); 185 | 186 | room->SetSide(North, new Wall); 187 | room->SetSide(South, new Wall); 188 | room->SetSide(East, new Wall); 189 | room->SetSide(West, new Wall); 190 | } 191 | } 192 | 193 | void StandardMazeBuilder::BuildDoor (int n1, int n2) { 194 | Room* r1 = _currentMaze->RoomNo(n1); 195 | Room* r2 = _currentMaze->RoomNo(n2); 196 | Door* d = new Door(r1, r2); 197 | r1->SetSide(CommonWall(r1,r2), d); 198 | r2->SetSide(CommonWall(r2,r1), d); 199 | } 200 | //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 201 | 202 | class EnchantedMazeBuilder : public MazeBuilder { 203 | public: 204 | EnchantedMazeBuilder(); 205 | 206 | virtual void BuildMaze(); 207 | virtual void BuildRoom(int); 208 | virtual void BuildDoor(int, int); 209 | 210 | virtual Maze* OrphanMaze(); 211 | private: 212 | Maze* _enchantedMaze; 213 | Direction CommonWall(Room*, Room*); 214 | }; 215 | 216 | class TwistyTurnyPassage : public Room { 217 | public: 218 | TwistyTurnyPassage(); 219 | virtual void Enter(); 220 | }; 221 | 222 | void EnchantedMazeBuilder::BuildDoor (int n1, int n2) { 223 | 224 | Room* r1 = _enchantedMaze->RoomNo(n1); 225 | Room* r2 = _enchantedMaze->RoomNo(n2); 226 | TwistyTurnyPassage* p = new TwistyTurnyPassage; 227 | Door* d1 = new Door(r1, p); 228 | Door* d2 = new Door(p, r2); 229 | r1->SetSide(CommonWall(r1,r2), d1); 230 | r2->SetSide(CommonWall(r2,r1), d2); 231 | } 232 | 233 | //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 234 | 235 | class CountingMazeBuilder : public MazeBuilder { 236 | public: 237 | CountingMazeBuilder(); 238 | 239 | virtual void BuildMaze(); 240 | virtual void BuildRoom(int); 241 | virtual void BuildDoor(int, int); 242 | virtual void AddWall(int, Direction); 243 | 244 | void GetCounts(int&, int&) const; 245 | private: 246 | int _doors; 247 | int _rooms; 248 | }; 249 | 250 | 251 | CountingMazeBuilder::CountingMazeBuilder () { 252 | _rooms = _doors = 0; 253 | } 254 | void CountingMazeBuilder::BuildRoom (int) { 255 | _rooms++; 256 | } 257 | void CountingMazeBuilder::BuildDoor (int, int) { 258 | _doors++; 259 | } 260 | void CountingMazeBuilder::GetCounts (int& rooms, int& doors) const { 261 | rooms = _rooms; 262 | doors = _doors; 263 | } 264 | 265 | 266 | //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 267 | #include "MazeGame.h" 268 | 269 | class BombedMazeGame : public MazeGame { 270 | public: 271 | BombedMazeGame(); 272 | virtual Wall* MakeWall() const 273 | { return new BombedWall; } 274 | virtual Room* MakeRoom(int n) const 275 | { return new RoomWithABomb(n); } 276 | }; 277 | 278 | 279 | class EnchantedMazeGame : public MazeGame { 280 | public: 281 | EnchantedMazeGame(); 282 | 283 | virtual Room* MakeRoom(int n) const 284 | { return new EnchantedRoom(n, WeaveSpell()); } 285 | virtual Door* MakeDoor(Room* r1, Room* r2) const 286 | { return new DoorNeedingSpell(r1, r2); } 287 | 288 | protected: 289 | Spell* WeaveSpell() const; 290 | }; 291 | 292 | 293 | //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 294 | 295 | Maze* MazeGame::CreateMaze() { 296 | Maze* aMaze = new Maze; 297 | Room* r1 = new Room(1); 298 | Room* r2 = new Room(2); 299 | Door *theDoor = new Door(r1, r2); 300 | 301 | aMaze->AddRoom(r1); 302 | aMaze->AddRoom(r2); 303 | 304 | r1->SetSide(North, new Wall); 305 | r1->SetSide(East, theDoor); 306 | r1->SetSide(South, new Wall); 307 | r1->SetSide(West, new Wall); 308 | r2->SetSide(North, new Wall); 309 | r2->SetSide(East, new Wall); 310 | r2->SetSide(South, new Wall); 311 | r2->SetSide(West, theDoor); 312 | 313 | return aMaze; 314 | } 315 | //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 316 | 317 | 318 | Maze* MazeGame::CreateMaze (MazeBuilder& builder) { 319 | builder.BuildMaze(); 320 | 321 | builder.BuildRoom(1); 322 | builder.BuildRoom(2); 323 | builder.BuildDoor(1, 2); 324 | 325 | return builder.GetMaze(); 326 | } 327 | 328 | Maze* MazeGame::CreateComplexMaze (MazeBuilder& builder) { 329 | builder.BuildRoom(1); 330 | // ... 331 | builder.BuildRoom(1001); 332 | 333 | return builder.GetMaze(); 334 | } 335 | 336 | //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 337 | 338 | Maze* MazeGame::CreateMaze (MazeFactory& factory) { 339 | Maze* aMaze = factory.MakeMaze(); 340 | Room* r1 = factory.MakeRoom(1); 341 | Room* r2 = factory.MakeRoom(2); 342 | Door* aDoor = factory.MakeDoor(r1, r2); 343 | 344 | aMaze->AddRoom(r1); 345 | aMaze->AddRoom(r2); 346 | 347 | r1->SetSide(North, factory.MakeWall()); 348 | r1->SetSide(East, aDoor); 349 | r1->SetSide(South, factory.MakeWall()); 350 | r1->SetSide(West, factory.MakeWall()); 351 | 352 | r2->SetSide(North, factory.MakeWall()); 353 | r2->SetSide(East, factory.MakeWall()); 354 | r2->SetSide(South, factory.MakeWall()); 355 | r2->SetSide(West, aDoor); 356 | 357 | return aMaze; 358 | } 359 | 360 | Maze* MazeGame::CreateSimpleMaze() { 361 | Maze* aMaze = MakeMaze(); 362 | 363 | Room* r1 = MakeRoom(1); 364 | Room* r2 = MakeRoom(2); 365 | Door *theDoor = MakeDoor(r1, r2); 366 | 367 | aMaze->AddRoom(r1); 368 | aMaze->AddRoom(r2); 369 | 370 | r1->SetSide(North, MakeWall()); 371 | r1->SetSide(East, theDoor); 372 | r1->SetSide(South, MakeWall()); 373 | r1->SetSide(West, MakeWall()); 374 | r2->SetSide(North, MakeWall()); 375 | r2->SetSide(East, MakeWall()); 376 | r2->SetSide(South, MakeWall()); 377 | r2->SetSide(West, theDoor); 378 | 379 | return aMaze; 380 | } 381 | 382 | Maze* MazeGame::MakeMaze () const { 383 | return new Maze; 384 | } 385 | Room* MazeGame::MakeRoom (int n) const { 386 | return new Room(n); 387 | } 388 | Wall* MazeGame::MakeWall () const { 389 | return new Wall; 390 | } 391 | Door* MazeGame::MakeDoor (Room* r1, Room* r2) const { 392 | return new Door(r1, r2); 393 | } 394 | 395 | 396 | //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 397 | 398 | // The offsets below are bad, but it makes code appear ok in text 399 | // Simply cut and paste 400 | 401 | //main() { 402 | //MazeGame game; 403 | //Maze* maze; 404 | // 405 | //maze = game.CreateMaze(); 406 | // 407 | //// Prototype 408 | // 409 | //MazePrototypeFactory prototypeFactory1( new Maze, 410 | // new Wall, 411 | // new Room, 412 | // new Door ); 413 | // 414 | //maze = game.CreateMaze(prototypeFactory1); 415 | // 416 | //MazePrototypeFactory prototypeFactory2(new Maze, 417 | // new BombedWall, 418 | // new RoomWithABomb, 419 | // new Door); 420 | // 421 | //maze = game.CreateMaze(prototypeFactory2); 422 | // 423 | //// Builder 424 | //StandardMazeBuilder sbuilder; 425 | //game.CreateMaze(sbuilder); 426 | // 427 | //maze = sbuilder.GetMaze(); 428 | // 429 | //int rooms, doors; 430 | //CountingMazeBuilder cbuilder; 431 | //game.CreateMaze(cbuilder); 432 | //cbuilder.GetCounts(rooms, doors); 433 | //cout << "The maze has " 434 | // << rooms << " rooms and " 435 | // << doors << " doors rooms\n"; 436 | //} 437 | 438 | 439 | --------------------------------------------------------------------------------