Circuit Simulator

In the general Composite Design Pattern there can be multiple primitive and composite component classes:

Note that Component, PrimitiveComponent, and CompositeComponent are all abstract. An example of this sort of thing would be parse trees where composite components might include composite statements such as while, if, switch, etc. Primitive Components might include expressions such as add, multiply, and assign.

Of course PrimitiveComponent and CompositeComponent don't need to be present if they don't have any responsibilities.

After listening to some ideas from students I decided there wasn't much need for a single base class for all composite components, but that a single base class for all primitive components would be useful. Here's the design I settled on:

Here's the test harness:

TestHalfAdder.java

In it I set up a half adder and test all combinations of inputs. Here's the output it produces:

1 + 1 = 0
cout = 1
1 + 0 = 1
cout = 0
0 + 1 = 1
cout = 0
0 + 0 = 0
cout = 0

I create my own simple version of Publisher and Subscriber:

Publisher.java

Subscriber.java

Wires are my concrete publishers:

Wire.java

A digital component is an abstract class that manages an array of input wires and an array of output wires:

DigitalComponent.java

Gates are concrete subscribers. They automatically subscribe to their input wires and implement update by calling the abstract method setOutputWires:

Gate.java

AND, OR, and NOT gates only differ in the ways they update their output wires:

AndGate.java

OrGate.java

NotGate.java

Note that the half adder makes all of its internal wires and gates, but overrides the addInput and addOutput methods inherited from DigitalComponent so that they are connected to the appropriate internal gates. This is important because a half adder may be an internal component of some other digital component such as an n-bit adder. In this case the n-bit adder will want to specify the input and output wires for the half adder.

HalfAdder.java