Decorator Pattern: attach additional responsibilities to an object dynamically. Decorators provide flexible alternative to sub classing for extending functionality.
Example
Account.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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
1 2 3 4 5 6 7 8 9 | package com.decoratorpattern.example; public class NoFrillsAccount extends Account{ public NoFrillsAccount(){ description = "NoFrills Account" ; } } |
AccountDecorator.java
1 2 3 4 5 | package com.decoratorpattern.example; public abstract class AccountDecorator extends Account { public abstract void enableFeature(); } |
InternetBanking.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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