Searching...
Saturday, 17 May 2014

Strategy Pattern Example

01:21

The Strategy design pattern enables a client to choose which algorithm to use from a family of algorithms and gives it a simple way to access it. The algorithms can also be expressed independently of the data they are using.

strategy

Here is one simple example to choose algorithm based on the requirement. Here i am creating two algorithm to recharge your mobile phones.

1. Create algorithms

Interface

package com.pretech.design;
public interface IRecharge {
	void recharge(double amount,String phonenumber);
}

Implementations

package com.pretech.design;
public class Airtel implements IRecharge {
	public void recharge(double amount, String phonenumber) {
		System.out.println("Airtel recharged successfully for " + phonenumber
				+ " amount Rs" + amount);
	}
}
package com.pretech.design;
public class Vodafone implements IRecharge {
	public void recharge(double amount, String phonenumber) {
		System.out.println("Vodafone recharged successfully for " + phonenumber
				+ " amount Rs" + amount);
	}
}

2. Create Context class

package com.pretech.design;
public class RechargeContext {
	private IRecharge recharge;
	public IRecharge getRecharge() {
		return recharge;
	}
	public void setRecharge(IRecharge recharge) {
		this.recharge = recharge;
	}
	public void recharge(double amount, String phonenumber) {
		recharge.recharge(amount, phonenumber);
	}
}

3. Create a Main class to apply algorithm

package com.pretech.design;
import javax.swing.JOptionPane;
public class RechargeMain {
	public static void main(String[] args) {
		String serviceProvider = JOptionPane.showInputDialog(null,
				"Enter Service Provider ");
		String phoneNumber = JOptionPane.showInputDialog(null,
				"Enter Phone Number ");
		String amount = JOptionPane.showInputDialog(null, "Enter Amount ");
		RechargeContext rc = new RechargeContext();
		if (serviceProvider.equalsIgnoreCase("Airtel")) {
			rc.setRecharge(new Airtel());
		}
		if (serviceProvider.equalsIgnoreCase("Vodafone")) {
			rc.setRecharge(new Vodafone());
		}
		rc.recharge(Double.valueOf(amount), phoneNumber);
	}
}

4. Run it


Input


image


image


image


Output



Airtel recharged successfully for 9898989898 amount Rs100.0


0 comments: