Thursday, 13 September 2012

Design Patterns by Examples – Decorator Pattern


Design Patterns by Examples – Decorator Pattern

Introduction

This series of articles will help you to build a good understanding of design patterns using different examples from real life and some from well-known frameworks or APIs. There are many articles around the web that discuss design patterns but they sometimes lack appropriate examples to quote. So, either their purpose stays unclear or we cannot memorize the patterns longer and sooner they slip out of mind. More importantly, we understand them but to employ within our problem domain is again out of the quest.
Expert designers reuse solutions that they had worked on in the past and they re-engage them whenever they faced with the same problems. Rookie designers can also use design patterns to solve their problems efficiently. This article is intended to help both naive and expert developers by making them understand the application of patterns and opening up new dimensions in solutions domain.

Decorator Pattern

For the sake of continuity, let’s look at the formal definition first.
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

At this stage you might not understand it clearly but as you go through the whole article you will gain better understanding of the pattern and would defiantly want to use it to solve your own domain problems.
In this part of the article I totally concerned about dynamic behaviors that most readers expect from pattern, decorator is not just design as well as analysis pattern too, we will discuss this in next part. So ignore NewState field in ConcreteDecoratorA for this time.

Problem Domain

To keep things simpler we take an example of a subsystem, where employees are working with different responsibilities (such as team members, team leads and a manager). A team member is responsible to do his assigned tasks and to coordinate with other members for the completion of group tasks. On the other hand, a team lead has to manage and collaborate with his team members and plan their tasks. Similarly, a manager has some extra responsibility over a team lead such as employee profiling, work assignment.
Following are the system entities and their behaviors:
Employee: calculate salary, join, terminate.
Team member: perform task, coordinate with others.
Team lead: planning, motivate.
Manager: assign task, employee profiling, create requirements.
There may be some other entities like Team, Task, etc. but my focus here is to convey the idea of a Decorator while keeping things simple and paying attention on root of pattern.

Traditional Approach

In such a system, the most followed approach is to make an employee super class and extend it to all three classes. Even this is an object oriented approach but it has some drawbacks.
Whenever a team member becomes a team lead, we have to create a new object of team lead and the previous object that points to that employee (team member) may be destroyed or archived. That’s not a recommended approach when employee is still a part of your organization. Same is the case with manager, when an employee turns into a manager from a team lead/team member.
Another case is when an employee can perform responsibilities of a team member as well as those of a team lead or a manager can perform team leads responsibilities. In that case you need to create two objects for the same employee which is totally wrong.
In these scenarios a team member/team lead can have extra responsibilities at run time. And their responsibilities can be assigned/revoked at run time.

Decorator Pattern Approach

Let’s see how design patterns help in these cases. If we look at Decorator Pattern it says:
Attach additional responsibilities to an object dynamically.
Wow, can it really solve my problem, let’s see.
At this moment we defector our previous approach in such a way that we always register just an Employee and TeamMember, TeamLead andManager will be decorator of that employee object.
Now, if we want to change responsibilities of an employee to manager we just need a new Manager (Decorator) and assigning that employee to it will solve our problem. Same is the case when a team lead’s responsibilities are revoked, and some other member becomes team lead, we just need to swap employee objects within TeamMember and TeamLead decorators.
As for the case where an employee can perform the responsibilities of a team member as well as those of a team lead, we just need TeamMember andTeamLead decorators that are pointing to same employee object.

Employee (Decorated/Component)

Implementation of Employee is as follows:

public interface
 Employee {

public void join(Date joinDate); 
public void terminate(Date terminateDate);

// other behaviors may reside (see sample code)
}

EmployeeImpl

This is the core implementation class of Employee interface, EmployeeImpl is given below:

public class
 EmployeeImpl implements Employee { 


// other behaviors and properties may reside (see sample code)
public void join(Date joinDate){
print(this.getName() + ” joined on “ + joinDate);
}

public void terminate(Date terminateDate){
print(this.getName() + ” terminate on “ + terminateDate);
}
}

EmployeeDecorator (Abstract Decorator)

This is an abstraction of Employee decorator, EmployeeDecorator is given below:

public abstract class EmployeeDecorator implements Employee {

protected Employee employee;

protected EmployeeDecorator(Employee employee) {
this.employee = employee;
}

// other behaviors may reside (see sample code)

public void join(Date joinDate) {
employee.join(joinDate);
}

public void terminate(Date terminateDate) {
employee.terminate(terminateDate);
}
}

TeamMember/TeamLead/Manager (Concrete Decorator)

These are concrete implementations of EmployeeDecorator, classes are given below:

public class TeamMember extends EmployeeDecorator {

protected TeamMember(Employee employee) {
super(employee);
}

public void performTask() {
print(employee.getName() + ” is performing his assigned tasks.”);
}

public void coordinateWithOthers() {
print(employee.getName() + ” is coordinating with other members of his team.”);
}

}

public class TeamLead extends EmployeeDecorator {

protected TeamLead(Employee employee) {
super
(employee);
}


public void planing() {
print(this.employee.getName() + ” is planing.”);
}

public void motivate() {
print(this.employee.getName() + ” is motivating his members.”);
}

}

public class Manager extends EmployeeDecorator {

protected Manager(Employee employee) {
super
(employee);
}

public void assignTask() {
print(this.employee.getName() + ” is assigning tasks.”);
}

public void profileEmployee() {
print(this.employee.getName() + ” is profiling employees.”);
}

public void createRequirments() {
print(this.employee.getName() + ” is creating requirement documents.”);
}

}

Some Example from APIs

There are many application of decorator in our routine APIs, like in I/O Streams and Readers use decorator pattern extensively.
In this example FilterInputStream, BufferedInputStream, DataInputStream and PushbackInputStream are decorators and FileInputStream andByteArrayInputStream are decorated objects.

InputStream inStream = new FileInputStream(“data.txt”);
Here inStream is a simple file input stream and


inStream = new BufferedInputStream(inStream);
Now inStream is decorated by BufferedInputStream decorator. At runtime the BufferedInputStream, which is a decorator, forwards the method call to its decorated object FileInputStream. The decorator will apply the additional functionality of buffering around FileInputStream.
SiteMash is also one of the examples of decorator pattern in java web frameworks to decorate page.

Basic steps to use Decorator

To implement the decorator pattern you can just follow these steps:
  1. Create an abstract class or interface that you want to decorate. (e.g; Employee) and provide concrete implementation of that class/interface by extending it.
  2. Create an abstract decorator (e.g; EmployeeDecorator) that contains pointer field of decorated class, decorator must extend same decorated class/interface. (e.g; Employee)
  3. Pass the object that you want to decorate in the constructor of decorator.
  4. Redirect methods of decorator to decorated class’s core implementation.
  5. Override methods where you need to change behavior.

Conclusions

  • Decorators are very flexible alternative of inheritance.
  • Decorators enhance (or in some cases restrict) the functionality of decorated objects.
  • They work dynamically to extend class responsibilities, even inheritance does same but in a static fashion (means compile time).

Design Patterns

The key to any solution is to understand the problem. When we have complete requirements of our problem domain, the proper analyses of those requirements will facilitate us when incorporating any possible changes in the future. We have to suggest some design that can support current requirements and any possible changes. Therefor we use our past experience or shared thoughts of experts (Design Patterns) to design an elegant, flexible and reusable solution, and try to avoid redesigning or at least minimize it.

Design patterns are solutions to design problems you find again and again in real world application development.
Design patterns are not actually APIs that can be programmed in classes and reused as they are, neither are they are not domain-specific designs for any application or module. Design patterns actually are guidelines for communicating objects and classes that are customized to solve a general design problem in a particular context.

Everything You Need to Know About iOS 6

Apple's new iPhone 5 hands-on! Experience


 At long last, the iPhone 5. We just got our hands on Apple's latest smartphone following its unveiling in San Francisco, and suffice it to say, it's a beautiful thing. Some might say we've been waiting for this moment since October 4th of last year, but another crowd may say that the real next-gen iPhone has been on the burner for much longer. Indeed, this is the first iPhone since June of 2010 to showcase an entirely new design, but it's obvious that Apple's not going to deviate far when it comes to aesthetics.
Apple followers will aptly recall Steve Jobs' quote in July of 2010 -- you know, that one about "no one" wanting a big phone, with current CEO Tim Cook seated just feet from Steve as the phrase was uttered. Now, however, Apple's inching ever closer to that very realm, with an elongated 4-inch display that enables new apps to take advantage of more pixels (1,136 x 640), while legacy apps can still operate within a familiar space. The phone itself doesn't feel too much different than the iPhone 4 and 4S; yes, it's a bit taller, but by keeping the width the same, you'll utilize a very familiar grasp to hold it.
In typical Apple fashion, even the finest details have been worked over tirelessly. The metal feels downright elegant to the touch, and the same line we've said time and time again applies here: there's no doubting the premium fit and finish when you clutch one of these things. Yeah, the headphone port's now on the bottom, but avid Galaxy Nexus iPod touch users shouldn't have too much trouble adjusting.







The rest of the leaks, by and large, were proven correct. High-speed LTE is being included in an iPhone for the first time, and the new Dock Connector is indeed smaller. Arguably, that's the change that'll cause the most headaches for longtime iDevice users -- if you've purchased an automobile, a speaker dock, or any of the other zillion iReady products in the past half-decade, you'll need to pony up for an adapter to make things work properly.
Apple's made this one lighter than before, and while the outgoing flagship never really felt heavy, this one feels impressively light. After all, it's both taller and lighter. The display -- which meets sRGB color specification -- now has an integrated touch layer, and Apple's not holding back when it calls it the "world's most advanced display." Sure enough, it looks beautiful. Of course, displays across the industry have been becoming increasingly sexy to look at, and Apple's newest most certainly pops when you ogle it. Is it better than the 4S? For sure, but it doesn't make the 4S' panel look dated by any means. The anti-glare measures implemented are highly appreciated, too.
The new A6 chip, in typical Apple style, hasn't revealed itself in terms of raw tech specs. But at a glance, it's definitely quicker than the chip in the 4S. Much like the speed increases between the iPhone 4 and 4S (and before that, the iPhone 3G vs. iPhone 3GS), they won't take you by storm right away. But, use it for half an hour and you'll have a hard time going back to a slower chip. The transitions are smoother, switching between apps is a bit quicker and everything just generally feels incrementally faster.
We'll be grabbing video and putting some of the new iOS 6-specific additions to the test, but for now, feel free to cast judgment on the design after peeking the gallery above.

Phone 5 vs. iPhone 4S: 7 Things Apple's New Device Has That iphone 4 Doesn't


Apple revealed its newest smartphone on Wednesday during a media event in San Francisco, showing off a slender new device that retails at a starting price of $199.
The iPhone 5, as expected, trumps the company's previous phones in a few crucial areas. For example, the latest device is powered by a faster A6 processor and can make calls and download data over speedy 4G LTE networks. But is it really worth it to spring for an iPhone 5, especially if you already own an iPhone 4S?
To help with your decision, check out our gallery (below) to see 7 things the iPhone 5 has that its predecessor doesn't. Then let us know what you think: Do you plan on snatching up the latest Apple smartphone? Is it truly a "revolutionary" upgrade, or do you think it left something to be desired?.

Want to know how the iPhone 5 stacks up against Samsung's Galaxy S3 and Microsoft's Lumia 920? Check out our handy spec chart (here).

eBay straightens out its logo after 17 years


Job Creation and Hiring in Silicon Valley, From the Perspective of a Entrepreneur


It's no surprise that startups and tech companies are the forerunners in job creation, and Silicon Valley startups are leading the pack. Silicon Valley startups create 11-percent more jobs than NYC startups and 38-percent more jobs than London startups. There is endless potential for innovation at startups in the valley, and these companies are looking for the best employees to bring their ideas to fruition. But, as fast as jobs are created, they can also be terminated in this extremely competitive industry. Startups have a high-risk profile and the potential to crash quickly as much as a high potential to be wildly successful, and I have been fortunate enough to have two successful companies under my belt, ClickAgents and BlueLithium, and am growing a third thriving company, RadiumOne. The key to the success I have been able to achieve, beyond crafting profitable products and services, is knowing what positions need to be created and hiring exceptional people to fill them.
Hiring has become increasingly difficult in Silicon Valley, where everyone is looking for the next best job. Everyone wants a big title and even bigger pay, but many are not willing to put in the work required to get there. I recently came across a quotation from Indiana University basketball coach Bob Knight that job seekers and hiring managers alike should reflect on. He said, "Most people have the will to win, few have the will to prepare to win." Winning takes time, winning takes practice, and, above all else, winning takes extreme dedication, commitment, and drive. Startups are the source of countless jobs, but not just anyone can succeed in the startup world. Hiring managers need to sift through the clutter to find first-rate candidates who are not only willing to go the extra mile but are also excited to do so.
At RadiumOne, we don't go about hiring in the conventional sense. While experience and education, etc. are important, of course, we look for passion -- and it is sometimes the hardest trait to find in potential employees.
We look for candidates who are hungry. They need to have a limitless appetite -- not just for the company and its products and services but for perfecting the little things. Take, for example, Susan Kare of Apple. Remember the first little Macintosh icon? That was all Susan. Her first title was "Macintosh Artist." She was passionate about pixels. Talk about the small stuff. Susan dedicated her time to placing pixels together in meaningful ways to create beautiful icons and graphics that ultimately changed desktop design. When an entire company is built with people who are passionate about the small stuff, the big picture is stunning.
We want to hire people with that same spirit and work ethic. We create jobs, but want to fill them with people looking for a career. Doing the 9-to-5 just isn't going to cut it. I'm not saying that you need to commit to work 80-hour weeks and lose all other aspects of your life; I'm just saying you can't come in, complete the tasks assigned to you, and leave. It takes an entrepreneur to thrive in another entrepreneur's company.
We want to have entrepreneurs working for us; people who will come up with a groundbreaking idea and, instead of just suggesting the idea, will spearhead an effort to get it implemented; people who will take on a brand new project with little direction or supervision; people who will do something they have no experience with, knowing that results may not be perfect but willing to take the risk anyways.
Entrepreneurs don't have bosses; they are their own bosses. They take it upon themselves to get work done, and they learn from mistakes along the way. We hire entrepreneurs like this. And when these entrepreneurs produce extraordinary work and need additional support, new jobs are created and the startup continues to grow.
Job creation is, in the long run, dependent on the employees a company hires from the get-go. It takes proactive and hardworking employees to grow departments and revenue. This remains especially true in startups, where each employee plays a critical role in that company's accomplishments. It is imperative to build a company with those who aspire to bring its vision to life.

Buying the iPhone 5? Ways to Convert your Old Iphone to iPhone 5


On Wednesday, Apple unveiled its much-anticipated iPhone 5 and also announced that the phone will be available in stores September 21 (pre-orders start September 14).

The two biggest differences with the latest iPhone: it will be thinner and lighter than previous models.

There are hundreds of tech Web sites currently analyzing the specs on the iPhone 5. So you won't get a breakdown here of why it is (or isn't) better than the iPhone 4S.

What you will get is a plan for the gadget you just gave up.

If you are going to buy or upgrade to the iPhone 5 this fall, what will you do with your old cellphone?

Sure, you could sell your phone to a retailer or back to Apple for cash. You could also throw it away, but the devices can let toxic metals seep into landfills. Worse yet, smartphones often wind up in developing countries where they cause health problems because they aren't properly disposed.

It's far easier -- and more meaningful -- to have your phone recycled in the U.S. so it ultimately becomes a calling card for a member of the military.

So go ahead. Buy the iPhone 5 and rejoice in the latest and greatest piece of mobile technology.

But don't leave your old phone sitting in a drawer or at the bottom of the trash.

This fall, recycle with a purpose. Giving back to our troops has never been easier.

Anyone know of other great ways to donate/recycle old cellphones? Share the knowledge!