Decorator Pattern

Decorator Pattern Java Design Pattern Tutorial
Decorator Pattern: attach additional responsibilities to an object dynamically. Decorators provide flexible alternative to sub classing for extending functionality.

Example

Account.java
package com.decoratorpattern.example;

public abstract class Account {
 
 String description;
 
 public String getDescription() {
  return description;
 }

 public void deposit() {
  System.out.format("Amount was deposited into %s Successfully \n",getDescription());

 }

 public void withdraw() {
  System.out.format("Amount  withdrawn from  %s Successfully \n",getDescription());

 }
}
NoFrillsAccount.java
package com.decoratorpattern.example;

public class NoFrillsAccount extends Account{

 public NoFrillsAccount(){
  description = "NoFrills Account";
 }

}
AccountDecorator.java
package com.decoratorpattern.example;

public abstract class AccountDecorator extends Account {
 public abstract void enableFeature();
}

InternetBanking.java
package com.decoratorpattern.example;

public class InternetBanking extends AccountDecorator{
 
 Account account;

 public InternetBanking(Account account) {
  this.account = account;
 }
 public String getDescription() {
  enableFeature();
  return account.getDescription() + " with Internet Banking" ;
 }
 @Override
 public void enableFeature() {
  System.out.format("Internet Banking Enabled for %s \n",account.getDescription());
 }
}
MobileBanking.java
package com.decoratorpattern.example;

public class MobileBanking extends AccountDecorator{
 
 Account account;

 public MobileBanking(Account account) {
  this.account = account;
 }

 public String getDescription() {
  return account.getDescription() + " with Mobile Banking" ;
 }
 
 @Override
 public void enableFeature() {
  System.out.format("Mobile Banking Enabled for %s \n",account.getDescription());
 } 

}
AccountTestDrive.java
package com.decoratorpattern.example;

public class AccountTestDrive {
 public static void main(String[] args) {
  Account noFrillsAccount = new NoFrillsAccount();
  // NoFrills Account having basic features like deposit and withdraw
  System.out.println(noFrillsAccount.getDescription());
  // Now with the help of AccountDecorator, we have enabled Internet banking for the NoFrills Account
  noFrillsAccount = new InternetBanking(noFrillsAccount);
  System.out.println(noFrillsAccount.getDescription());

 }

}


Home

No comments:

Post a Comment