Categories
Algorithms & Design Design Pattern

DAO Pattern

Employee.java

public class Employee {

	private String firstName, lastName;
	private String designation;
	private String employeeCode;
	public Employee(String employeeCode, String firstName, String lastName, String designation){
		this.employeeCode=employeeCode;
		this.firstName=firstName;
		this.lastName=lastName;
		this.designation=designation;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public String getDesignation() {
		return designation;
	}
	public void setDesignation(String designation) {
		this.designation = designation;
	}
	public String getEmployeeCode() {
		return employeeCode;
	}
	public void setEmployeeCode(String employeeCode) {
		this.employeeCode = employeeCode;
	}
	
	public String toString(){
		return "[EmployeeCode : "+employeeCode+", LastName : "+lastName+", FirstName : "+firstName+", Designation : "+designation+"]";
	}
}

EmployeeDAO.java

import java.util.HashMap;
import java.util.Map;

public class EmployeeDAO {
	
	protected Map employeeMap;
	
	public EmployeeDAO(){
		employeeMap = new HashMap();
	}

	public Employee getEmployee(String employeeCode){
		return employeeMap.get(employeeCode);
	}
	
	public void addEmployee(String employeeCode, String firstName, String lastName, String designation){
		employeeMap.put(employeeCode, new Employee(employeeCode,firstName,lastName,designation));
	}
	
	public void updateEmployee(Employee employee){
		employeeMap.put(employee.getEmployeeCode(), employee);
	}
	
}

DAOPatternDemo.java

public class DAOPatternDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		//update database
		EmployeeDAO dao = new EmployeeDAO();
		dao.addEmployee("1", "Tina", "Roz", "PM");
		dao.addEmployee("2", "Mina", "Koze", "Lead");
		dao.addEmployee("3", "Ina", "Arase", "Developer");
		dao.addEmployee("4", "Hina", "Mase", "Tester");
		
		//get employee with code 4
		System.out.println("EmployeeCode :4 "+dao.getEmployee("4"));
		
		//update Designation of Employee3
		Employee employee3 = dao.getEmployee("3");
		employee3.setDesignation("Sr. Developer");
		dao.updateEmployee(employee3);
		System.out.println("After update Employee : 3 "+ dao.getEmployee("3"));
		
	}

}

Output

Categories
Algorithms & Design Design Pattern

Visitor Pattern

ComputerElement.java

public abstract class ComputerElement {
	
	public double price;//prices are in INR
	
	public ComputerElement(double price){
		this.price=price;
	}
	
	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	public abstract double accept(ComputerElementVisitor visitor);
	
	
}

ComputerElementVisitor.java

public abstract class ComputerElementVisitor {

	public abstract double visit(CRTMonitor crtMonitor);
	public abstract double visit(Keyboard keyboard);
	public abstract double visit(LCDMonitor lcdMonitor);
	public abstract double visit(Mouse mouse);
	public abstract double visit(WirelessKeyboard wirelessKeyboard);
	public abstract double visit(WirelessMouse wirelessMouse);
}

CRTMonitor.java

public class CRTMonitor extends ComputerElement {

	public CRTMonitor(double price){
		super(price);
	}
	
	@Override
	public double accept(ComputerElementVisitor visitor) {
		// TODO Auto-generated method stub
		return visitor.visit(this);
	}

}

LCDMonitor.java

public class LCDMonitor extends ComputerElement {

	public LCDMonitor(double price){
		super(price);
	}
	@Override
	public double accept(ComputerElementVisitor visitor) {
		// TODO Auto-generated method stub
		return visitor.visit(this);
	}

}

Keyboard.java

public class Keyboard extends ComputerElement {

	public Keyboard(double price){
		super(price);
	}
	@Override
	public double accept(ComputerElementVisitor visitor) {
		// TODO Auto-generated method stub
		return visitor.visit(this);
	}

}

WirelessKeyboard.java

public class WirelessKeyboard extends ComputerElement {

	public WirelessKeyboard(double price) {
		// TODO Auto-generated constructor stub
		super(price);
	}
	
	@Override
	public double accept(ComputerElementVisitor visitor) {
		// TODO Auto-generated method stub
		return visitor.visit(this);
	}

}

Mouse.java

public class Mouse extends ComputerElement {

	public Mouse(double price){
		super(price);
	}
	@Override
	public double accept(ComputerElementVisitor visitor) {
		// TODO Auto-generated method stub
		return visitor.visit(this);
	}

}

WirelessMouse.java

public class WirelessMouse extends ComputerElement {

	public WirelessMouse(double price) {
		// TODO Auto-generated constructor stub
		super(price);
	}
	@Override
	public double accept(ComputerElementVisitor visitor) {
		// TODO Auto-generated method stub
		return visitor.visit(this);
	}

}

ComputerAssembly.java

import java.util.ArrayList;

public class ComputerAssembly {
	
	private ArrayList   elements;
	
	public ComputerAssembly(){
		elements = new ArrayList();
	}
	
	public void addElement(ComputerElement element){
		elements.add(element);
	}

	public double calculateDiscountedPrice(ComputerElementVisitor discountVisitor){
		double price = 0;
		
		for (ComputerElement computerElement : elements) {
			price = price + computerElement.accept(discountVisitor);
		}
		
		return price;
	}
}

ComputerElementDiscountVisitor.java

public class ComputerElementDiscountVisitor extends ComputerElementVisitor {

	@Override
	public double visit(CRTMonitor crtMonitor) {
		double discount = 10;
		double crtPrice = crtMonitor.getPrice();
		double discountedPrice = crtPrice - (crtPrice*10/100);
		return discountedPrice;
	}

	@Override
	public double visit(Keyboard keyboard) {
		double discount = 5;
		double keyboardPrice = keyboard.getPrice();
		double discountedPrice = keyboardPrice - (keyboardPrice*10/100);
		return discountedPrice;
	}

	@Override
	public double visit(LCDMonitor lcdMonitor) {
		double discount = 2;
		double lcdMonitorPrice = lcdMonitor.getPrice();
		double discountedPrice = lcdMonitorPrice - (lcdMonitorPrice*10/100);
		return discountedPrice;
	}

	@Override
	public double visit(Mouse mouse) {
		double discount = 5;
		double mousePrice = mouse.getPrice();
		double discountedPrice = mousePrice - (mousePrice*10/100);
		return discountedPrice;
	}

	@Override
	public double visit(WirelessKeyboard wirelessKeyboard) {
		double discount = 1;
		double wirelessKeyboardPrice = wirelessKeyboard.getPrice();
		double discountedPrice = wirelessKeyboardPrice - (wirelessKeyboardPrice*10/100);
		return discountedPrice;
	}

	@Override
	public double visit(WirelessMouse wirelessMouse) {
		double discount = 1;
		double wirelessMousePrice = wirelessMouse.getPrice();
		double discountedPrice = wirelessMousePrice - (wirelessMousePrice*10/100);
		return discountedPrice;
	}

}

VisitorPatternDemo.java

public class VisitorPatternDemo {

	public static void main(String[] args) {

		//Prepare list of Elements in store
		CRTMonitor crtMonitor = new CRTMonitor(5000);
		LCDMonitor lcdMonitor  = new LCDMonitor(10000);
		Keyboard keyboard = new Keyboard(2000);
		WirelessKeyboard wirelesKeyboard = new WirelessKeyboard(3000);
		Mouse mouse  = new Mouse(1000);
		WirelessMouse wMouse  = new WirelessMouse(2500);

		//discount calculator visitor for each element
		ComputerElementVisitor discountVisitor = new ComputerElementDiscountVisitor();

		
		
		//Prepare Computer with LCD and wirelss elements
		System.out.println("---------------------------------------------");
		System.out.println("Prepare Computer with LCD and wirelss elements");
		ComputerAssembly assembly1 = new ComputerAssembly();
		assembly1.addElement(lcdMonitor);
		assembly1.addElement(wMouse);
		assembly1.addElement(wirelesKeyboard);
		System.out.println("applied discount price :"+assembly1.calculateDiscountedPrice(discountVisitor));
		
		
		
		//Prepare Computer with CRT and wirelss elements
		System.out.println("---------------------------------------------");
		System.out.println("Prepare Computer with CRT and wirelss elements");
		ComputerAssembly assembly2 = new ComputerAssembly();
		assembly2.addElement(crtMonitor);
		assembly2.addElement(wMouse);
		assembly2.addElement(wirelesKeyboard);
		System.out.println("applied discount price :"+assembly2.calculateDiscountedPrice(discountVisitor));
		
		//Prepare computer with CRT and wired element
		System.out.println("---------------------------------------------");
		System.out.println("Prepare Computer with CRT and wirelss elements");
		ComputerAssembly assembly3 = new ComputerAssembly();
		assembly3.addElement(crtMonitor);
		assembly3.addElement(mouse);
		assembly3.addElement(keyboard);
		System.out.println("applied discount price :"+assembly3.calculateDiscountedPrice(discountVisitor));
		
	}

}

Output

Categories
Algorithms & Design Design Pattern

Template Pattern

DocumentReader.java

import java.io.File;

public abstract class DocumentReader {
	
	protected String fileName;

	public DocumentReader(String fileName){
		this.fileName=fileName;
	}
	
	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public void processFile(){
		boolean isPresent = checkforFilePresent();
		if(!isPresent)
			System.out.println("Could not find a file::"+fileName);
		openFile();
		readFile();
		closeFile();
	}
	
	public boolean checkforFilePresent(){
		System.out.println("checking if file is present::"+fileName);
		return true;
	}

	public abstract void openFile();
	public abstract void readFile();
	public void closeFile(){
		System.out.println("closing the file::"+fileName);
	}
}

PDFDocumentReader.java

public class PDFDocumentReader extends DocumentReader{

	public PDFDocumentReader(String fileName){
		super(fileName);
	}
	public void openFile(){
		System.out.println("opening the pdf file with Acrobat reader::"+fileName);
	}
	public void readFile(){
		System.out.println("reading the pdf file with Acrobat reader::"+fileName);
	}


}

WordDocumentReader.java

public class WordDocumentReader extends DocumentReader{
	public WordDocumentReader(String fileName){
		super(fileName);
	}
	
	public void openFile(){
		System.out.println("opening the word file with MS office::"+fileName);
	}
	public void readFile(){
		System.out.println("reading the word file with MS office::"+fileName);
	}

}

TemplatePatternDemo.java

public class TemplatePatternDemo {

	public static void main(String[] args) {
	 //read the ABC.PDF file
		DocumentReader reader = new PDFDocumentReader("ABC.pdf");
		reader.processFile();
		
		//read XYZ.doc file
		reader = new WordDocumentReader("XYZ.doc");
		reader.processFile();

	}

}

Output

Categories
Algorithms & Design Design Pattern

Strategy Pattern

Context.java

public class Context {
	
	private Strategy strategy;

	public Strategy getStrategy() {
		return strategy;
	}

	public void setStrategy(Strategy strategy) {
		this.strategy = strategy;
	}

	public int execute(int a, int b){
		return strategy.execute(a, b);
	}
}

Strategy.java

public abstract class Strategy {

	public abstract int execute(int a, int b);
}

AdditionStrategy.java

public class AdditionStrategy extends Strategy {

	@Override
	public int execute(int a, int b) {
		// TODO Auto-generated method stub
		return a+b;
	}

}

SubstractionStrategy.java

public class SubstractionStrategy extends Strategy {

	@Override
	public int execute(int a, int b) {
		// TODO Auto-generated method stub
		return a-b;
	}

}

MultiplyStrategy.java

public class MultiplyStrategy extends Strategy {

	@Override
	public int execute(int a, int b) {
		// TODO Auto-generated method stub
		return a*b;
	}

}

DivisionStrategy.java

public class DivisionStrategy extends Strategy {

	@Override
	public int execute(int a, int b) {
		// TODO Auto-generated method stub
		return a/b;
	}

}

PowerStrategy.java

public class PowersStrategy extends Strategy {

	@Override
	public int execute(int a, int b) {
		// TODO Auto-generated method stub
		return (int)Math.pow(a, b);
	}

}

StrategyPatternDemo.java

import java.util.Scanner;

public class StrategyPatternDemo {

	public static void main(String[] args) {

		Strategy addition = new AdditionStrategy();
		Strategy substraction  = new SubstractionStrategy();
		Strategy multiply = new MultiplyStrategy();
		Strategy division = new DivisionStrategy();
		Strategy powers = new PowersStrategy();
		
		
		Context context = new Context();
		
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Enter number for a ::");
		int a = sc.nextInt();
		System.out.println("Enter number for b :: ");
		int b = sc.nextInt();
		
		context.setStrategy(addition);
		System.out.println("by addition Strategy ::::"+context.execute(a, b));
		
		context.setStrategy(substraction);
		System.out.println("by substraction Strategy ::::"+context.execute(a, b));
		
		context.setStrategy(multiply);
		System.out.println("by multiply Strategy ::::"+context.execute(a, b));
		
		context.setStrategy(division);
		System.out.println("by division Strategy ::::"+context.execute(a, b));
		
		context.setStrategy(powers);
		System.out.println("by powers Strategy ::::"+context.execute(a, b));
		
	}

}

Output

Categories
Algorithms & Design Design Pattern

Null Pattern

Employee.java

public class Employee {
	protected String firstName,lastName;
	protected String employeeId;
	public Employee(String firstName, String lastName,String employeeId){
		this.firstName=firstName;
		this.lastName=lastName;
		this.employeeId=employeeId;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getEmployeeId() {
		return employeeId;
	}

	public void setEmployeeId(String employeeId) {
		this.employeeId = employeeId;
	}

	public String getfirstName() {
		return firstName;
	}

	public void setlastName(String lastName) {
		this.lastName = lastName;
	}
}

RegisteredEmployee.java

public class RegisteredEmployee extends Employee {
	
	public RegisteredEmployee(String firstName, String lastName,String employeeId){
		super(firstName,lastName,employeeId);
	}
	
	@Override
	public String toString(){
		return "firstName :"+firstName+", lastName : "+lastName;
	}

}

NullEmployee.java

public class NullEmployee extends Employee{

	public NullEmployee(){
		super(null,null,null);
	}
	public String toString(){
		
		return "Employee does not exist";
	}
}

EmployeeRegister.java

import java.util.HashMap;
import java.util.Map;

public class EmployeeRegister {

	private Map employeeList;
	
	public EmployeeRegister(){
		employeeList = new HashMap();
	}
	public Employee getEmployee(String employeeId){
		
		Employee employee = employeeList.get(employeeId);
		if(employee==null)
			employee = new NullEmployee();
		return employee;
	}
	
	public void registerEmployee(Employee employee){
		if(employee instanceof NullEmployee)
			return;
		employeeList.put(employee.getEmployeeId(), employee);
	}
}

NullPointerDemo.java

public class NullPointerDemo {

	public static void main(String[] args) {

		//Prepare Employee register
		EmployeeRegister register = new EmployeeRegister();
		
		//employee1
		register.registerEmployee(new RegisteredEmployee("Ina","Kose","111"));
		register.registerEmployee(new RegisteredEmployee("Mina","Mose","112"));
		register.registerEmployee(new RegisteredEmployee("Hina","Gose","113"));
		register.registerEmployee(new RegisteredEmployee("Tina","Bose","114"));
		
		//get Employee 113
		System.out.println("Employee 113 :"+register.getEmployee("113"));
		System.out.println("Employee 112 :"+register.getEmployee("112"));
		System.out.println("Employee 115 :"+register.getEmployee("115"));
	}

}

Output

Categories
Algorithms & Design Design Pattern

State Pattern

State.java

public abstract class State {

	public abstract void doAction();
}

StartState.java

public class StartState extends State {

	@Override
	public void doAction() {
		// TODO Auto-generated method stub
		System.out.println("process is in starting state but not started");
	}

}

InWorkState.java

public class InWorkState extends State {

	@Override
	public void doAction() {
		// TODO Auto-generated method stub
		System.out.println("Process is in In Work state, pls wait for finish.");
	}

}

CompleteState.java

public class CompleteState extends State {

	@Override
	public void doAction() {
		// TODO Auto-generated method stub
		System.out.println("Process is in Complete state, pls collect output");
	}

}

ContextProcess.java

public class ContextProcess {

	private State state;

	public State getState() {
		return state;
	}

	public void setState(State state) {
		this.state = state;
	}
	
	public void displayStatus(){
		state.doAction();
	}
}

StatePatternDemo.java

public class StatePatternDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//create the context Process Object
		ContextProcess process = new ContextProcess();
		
		State start = new StartState();
		State inWork = new InWorkState();
		State complete = new CompleteState();
		
		//set process to Start
		process.setState(start);
		process.displayStatus();
		
		//set process to in work
		process.setState(inWork);
		process.displayStatus();
		
		//set process to complete
		process.setState(complete);
		process.displayStatus();

	}

}

Output

Categories
Algorithms & Design Design Pattern

Observer Pattern

Subject.java

import java.util.ArrayList;
import java.util.List;

public class Subject {

	private int state;
	public List subscribers ;

	public Subject(){
		subscribers=new ArrayList();
	}
	public int getState() {
		return state;
	}

	public void setState(int state) {
		this.state = state;
	}
	public void attach(Observer observer){
		subscribers.add(observer);
	}
	public void sendNotification(){
		for (Observer observer : subscribers) {
			observer.execute(state);
		}
	}
	
}

Observer.java

public abstract class Observer {

	public abstract void execute(int state);
}

CalculateSquareObserver.java

public class CalculateSquareObserver extends Observer {

	@Override
	public void execute(int state) {
		// TODO Auto-generated method stub
		System.out.println("Square is ::"+(state*state));
	}

}

CalculateEvenOddObserver.java

public class CalculateEvenOddObserver extends Observer {

	@Override
	public void execute(int state) {
		// TODO Auto-generated method stub
			if(state%2==0)
				System.out.println(state + " is even number");
			else 
				System.out.println(state + " is odd number");
	}

}

ObserverPatternDemo.java

import java.util.Scanner;

public class ObserverPatternDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		//Create Subject
		Subject subject = new Subject();
		
		//Create observers
		Observer sqrObserver = new CalculateSquareObserver();
		Observer evenOddObserver = new CalculateEvenOddObserver();
		
		//attach observers
		subject.attach(sqrObserver);
		subject.attach(evenOddObserver);
		
		System.out.println("Enter the number :" );
		Scanner sc = new Scanner(System.in);
		subject.setState(sc.nextInt());
		
		subject.sendNotification();
	}

}

Output

Categories
Algorithms & Design Design Pattern

Memento Pattern

Memento.java

public class Memento {

	private String currentText;
	public Memento(String text){
		this.currentText = text;
	}
	
	public String getCurrentText(){
		return currentText;
	}
}

CareTaker.java

import java.util.ArrayList;

public class CareTaker {

	private ArrayListmementoList;
	
	public CareTaker(){
		mementoList = new ArrayList();
	}
	public void push(Memento memento){
		mementoList.add(memento);
	}
	public Memento pop(){
		Memento memento = mementoList.get(mementoList.size()-1);
		mementoList.remove(mementoList.size()-1);
		return memento;
	}
}

NotePad.java

public class NotePad {

	String currentText;
	private CareTaker careTaker;

	public NotePad(){
		careTaker = new CareTaker();
		currentText="";
	}
	public String getCurrentText() {
		return currentText;
	}
	public void setCurrentText(String currentText) {
		this.currentText = currentText;
	}
	public void appendString(String message){
		this.currentText+=message;
	}
	
	public Memento saveStateToMemento(){
		return new Memento(currentText);
	}
	
	public int hashCode() {
		return careTaker.hashCode();
	}
	public String toString() {
		return careTaker.toString();
	}
	public boolean equals(Object arg0) {
		return careTaker.equals(arg0);
	}
	
	public void save(){
		careTaker.push(new Memento(this.currentText));
	}
	public void undo(){
		Memento memento = careTaker.pop();
		this.currentText=memento.getCurrentText();
	}
}

MementoPatternDemo.java

import java.util.Scanner;

public class MementoPatternDemo {

	public static void main(String[] args) {
		//create the notepad class
		NotePad notepad = new NotePad();
		Scanner sc = new Scanner(System.in);
		
		//enter the string
		System.out.println("enter the string");
		notepad.appendString(sc.next());
		notepad.save();
		System.out.println("current Text saved ::"+notepad.getCurrentText());
		
		//enter next string
		System.out.println("enter the string");
		notepad.appendString(sc.next());
		notepad.save();
		System.out.println("current Text saved ::"+notepad.getCurrentText());
		
		//enter next string
		System.out.println("enter the string");
		notepad.appendString(sc.next());
		System.out.println("current Text saved ::"+notepad.getCurrentText());
				
		
		notepad.undo();
		System.out.println("after undo 1 current Text saved ::"+notepad.getCurrentText());
		notepad.undo();
		System.out.println("adter undo 2 current Text saved ::"+notepad.getCurrentText());
		
		
	}

}

Output

Categories
Algorithms & Design Design Pattern

Mediator Pattern

Person.java

public class Person {
	
	private String firstName, lastName;
	private ChatGroup chatGroup;

	public ChatGroup getChatGroup() {
		return chatGroup;
	}
	public void setChatGroup(ChatGroup chatGroup) {
		this.chatGroup = chatGroup;
	}
	public Person(String firstName, String lastName){
		this.firstName=firstName;
		this.lastName=lastName;
	}
	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	
	public String toString(){
		return lastName+","+firstName;
	}

	public void sendMessage(String message){
		chatGroup.sendMessage(this, message);
	}
}

ChatGroup.java

import java.util.Date;

public class ChatGroup {

	public void sendMessage(Person person, String message){
		System.out.println(new Date()+"\n"+person +":"+message);
		System.out.println("------------------------------------------------");
	}
	
}

MediatorPatternDemo.java

public class MediatorPatternDemo {

	public static void main(String[] args) {
		//create Persons
		Person Mina = new Person("Mina","Jose");
		Person Tina = new Person("Tina","Bose");
		Person Hina = new Person("Hina","Firose");
		Person Ina = new Person("Ina","Mose");
		
		//Create Group of persons
		ChatGroup chatGroup = new ChatGroup();
		Mina.setChatGroup(chatGroup);
		Tina.setChatGroup(chatGroup);
		Hina.setChatGroup(chatGroup);
		Ina.setChatGroup(chatGroup);
		
		//send the messages
		Mina.sendMessage("Hey I am mina technician");
		Tina.sendMessage("Hey I am tina, I play Guitar");
		Hina.sendMessage("Hello I am Hina, I love violin");
		Ina.sendMessage("Hi everybody, I am singer");
		
		
	}

}

Output

Categories
Algorithms & Design Design Pattern

Iterator Pattern

Account.java

public class Account {

	String customerName;
	public String getCustomerName() {
		return customerName;
	}
	public void setCustomerName(String customerName) {
		this.customerName = customerName;
	}
	public int getAccountNo() {
		return accountNo;
	}
	public void setAccountNo(int accountNo) {
		this.accountNo = accountNo;
	}
	int accountNo;
	public Account() {
		// TODO Auto-generated constructor stub
	}
	public Account(String customerName, int accNo){
		this.customerName=customerName;
		this.accountNo=accNo;
	}
	public String toString(){
		return "[Account Holder Name : "+customerName+", Account No : "+accountNo+"]";
	}
}

AccountList.java

import java.util.ArrayList;

public class AccountList {

	private ArrayList accountList ;
	
	public AccountList() {
		// TODO Auto-generated constructor stub
		this.accountList=new ArrayList();
	}
	public void push(Account account){
		this.accountList.add(account);
	}
	public Account get(int index){
		return accountList.get(index);
	}
	public int getSize(){
		return accountList.size();
	}
}

AccountListIterator.java

public class AccountListIterator {
	private int index;
	AccountList accountList;
	
	public AccountListIterator(AccountList accList) {
		this.accountList=accList;
		index=0;
	}
	public Account next(){
		return accountList.get(index++);
	}
	public boolean hasNext(){
		return index<accountList.getSize();
	}
}

IteratorPatternDemo.java

public class IteratorPatternDemo {

	public IteratorPatternDemo() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		Account acc1 = new Account("Jany Jose", 123);
		Account acc2 = new Account("Hana Mose", 223);
		Account acc3 = new Account("Tina Bose", 323);
		Account acc4 = new Account("Mina Kose", 423);
		
		AccountList accList = new AccountList();
		accList.push(acc1);
		accList.push(acc2);
		accList.push(acc3);
		accList.push(acc4);
		
		AccountListIterator itr  = new AccountListIterator(accList);
		while(itr.hasNext()){
			System.out.println("Account : "+itr.next());
		}
	}

}

Output

Design a site like this with WordPress.com
Get started