Idiotic guide to the Bridge Pattern

An idiotic post teaching you my solution to the Bridge Pattern and other nonsense.

The bridge pattern is a design pattern used in software engineering which is meant to “decouple an abstraction from its implementation so that the two can vary independently”. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes. ~Wikipedia

So here is my solution:


The “Stupidity” Class


abstract class Stupidity{
	Idiot idiot;
	
	public void setIdiot(Idiot idiot){
		this.idiot = idiot;
	}
	
	public abstract void printQuality();

	public void doAction(){
		System.out.println(idiot.getAction());
	}
}

“Ignorance” and “Foolishness”, both derived from Stupidity

class Ignorance extends Stupidity{
	@Override
	public void printQuality(){
		System.out.println("I am ignorant!");
	}
}

class Foolishness extends Stupidity{
	@Override
	public void printQuality(){
		System.out.println("I am a fool!");
	}
}

The “Idiot” Interface

interface Idiot{
	public String getAction();
}

Implementations of “Idiot”

class FatIdiot implements Idiot{
	@Override
	public String getAction(){
		return "Idiotically Fat!";
	}
}

class ThinIdiot implements Idiot{
	@Override 
	public String getAction(){
		return "Idiotically Thin!";
	}
}

The “main” method, demonstrates the above

public class Main {
	public static void main(String[] args){
		Stupidity stupidity = new Ignorance();
		stupidity.printQuality();
		
		stupidity.setIdiot(new FatIdiot());
		stupidity.doAction();
		
		stupidity.setIdiot(new ThinIdiot());
		stupidity.doAction();
		
		stupidity = new Foolishness();
		stupidity.printQuality();
		
		stupidity.setIdiot(new FatIdiot());
		stupidity.doAction();
		
		stupidity.setIdiot(new ThinIdiot());
		stupidity.doAction();		
	}
}

Output:

I am ignorant!
Idiotically Fat!
Idiotically Thin!

I am a fool!
Idiotically Fat!
Idiotically Thin!

As you can see, the bridge pattern makes “Stupidity” more flexible, different implementations of “Idiot” can literally be plugged into it. Which makes it more generic and improves design.

Advertisements

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