Generic Singletons with C#

C# gives you most of the generic powers that also Java has. So if one were so inclined he could write a generic singleton class. This approach would free implementing classes (and their developers) from handling the instance reference and providing the getInstance() method. Granted this is not a lot of work per instance but even an avalanche is made up from tiny snowflakes.

This example was written to be used inside the Unity game development framework. Unity takes care of the initialisation, so we only have to worry about keeping the reference.

Two base classes are needed to get around some limitations of C# generic implementations. An untyped class which stands at the root of the inheritance tree (“AbstractValueController”) and a typed Class which extends this BaseClass (“ValueController”).

1) The untyped BaseClass which I chose to declare abstract to make it more distinguishable:

public class AbstractValueController : MonoBehaviour {
}

2) The typed Class which contains the actual singleton logic:

public abstract class ValueController<SubType> : AbstractValueController
		where SubType : AbstractValueController {

	//the reference is saved as the root type but gets casted upon retrieval
	protected static AbstractValueController instance;
	public static SubType Instance { get { return (SubType) instance; } }

	//the Awake() Method is part of the UnityFramework and very similar to a constructor
	public virtual void Awake() {
		instance = this;
	}
}

3) An example implementing class which you want to be a singleton:

//class is typed with its own type for the singleton logic to work
public class Controller : ValueController<Controller> {
	//no singleton code needed  ... neat
}

Fuzzy Logic with jFuzzyLogic

jFuzzyLogic is an easy to use library for fuzzy logic computations.
After adding the Package to your projects classpath you only need a couple of lines of code to include and run fuzzy logic computations. Basically it is just a matter of setting variables, running the computation and then later retrieving the output parameters.

fis.setVariable("input1", arg1);
fis.setVariable("input2", arg2);

// Evaluate
fis.evaluate();
Variable out = fis.getVariable("out");
System.out.println("Output = "+out.getValue());

Sources: