The “Hard Shell Soft Center” Pattern

Maybe there’s a real name for this 😉 but that’s what I like to think of it as.

Also — full disclosure — I never use this pattern. But it’s fun to think about.

It comes down to how do you expose functionality with shared state.

Almost everyone who’s stuck in 2001 immediately jumps to Singleton. The basic idea of the Singleton pattern is that you’re protecting methods on shared state. If there’s no shared state in a class, then Singleton is ridiculous and worse than worthless. (Because of all the design limitations it inflicts.)

The idea of Singleton is that there is a static factory method call “getInstance()” that is guaranteed to always return the same instance. So everyone who calls “getInstance()” gets a specific instance that everyone else gets, and that’s how we share state.

I see static methods as “hard” because they are rigid and tied to one implementation class at compile time. Instance methods are “soft” and can be overridden or provided from an alternate implementation. So Singleton’s like a “hard factory that produces a specific, shared, soft instance”.

But another way to share state is to hide the state information in an internal object, and instead of exposing the object, you create a hard wrapper around it. So it’s like this:


public class HardShell {

private static SoftCenter center = new SoftCenter();

public static doSomething() {
center.doSomething();
}
}

// act on the shared information in the SoftCenter object without exposing it
HardShell.doSomething();

..and if you’re smart you’ll have some sort of “setCenter(newCenter)” call that allows you to swap out the object you’re protecting.

That way, the hard shell becomes a sort of Locator for the instance that you’re trying to hide. Kind of an interesting idea.

I never use that pattern, though. 😉

Advertisements

Leave a comment

Filed under computer OOD, design patterns, opinionizing

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s