View RSS Feed

fatabass

Using of Inner Classes

Rating: 1 votes, 1.00 average.
by , 02-06-2012 at 01:15 AM (849 Views)
Java Code:
package myPackage2;

public abstract class Event 
{
	private long eventTime;
	protected final long delayTime;
	
	public Event(long delayTime)
	{
		this.delayTime = delayTime;
		start();
	}
	
	public void start()
	{
		eventTime = System.nanoTime() + 2*delayTime;
	}
	
	public boolean ready()
	{
		return System.nanoTime() >= eventTime;
	}
	
	public abstract void action();

}
Java Code:
package myPackage2;

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

public class Controller 
{
	private List<Event> eventList = new ArrayList<Event>();
	
	public void addEvent(Event c)
	{
		eventList.add(c);
	}
	
	public void run()
	{
		System.out.println("Run!");

		while(eventList.size()>0)
		{
			//System.out.println("Eventlist size: " + eventList.size());

			for(Event e: new ArrayList<Event>(eventList))
				if(e.ready())
				{
					System.out.println(e);
					e.action();
					eventList.remove(e);
				}
		}
	}

}
Java Code:
package myPackage2;

public class GreenHouseControls extends Controller 
{
	private boolean light = false;
	
	GreenHouseControls()
	{
		this.addEvent(new Bell(0));
	}
	
	public class LightOn extends Event
	{
		public LightOn(long delayTime)
		{
			super(delayTime);
		}
		
		public void action()
		{
			
			light = true;
		}
		
		public String toString()
		{
			return "Light is on";
		}
	}
	
	public class LightOff extends Event
	{
		public LightOff(long delayTime)
		{
			super(delayTime);
		}
		public void action()
		{
			light = false;
		}
		
		public String toString()
		{
			return "Light is off";
		}
		
	}
	
	public class Bell extends Event
	{
		public Bell(long delayTime)
		{
			super(delayTime);
		}
		
		public void action()
		{
			
		}
		
		public String toString()
		{
			return "Bing!";
		}
	}
}
Java Code:
package myPackage2;

public class GreenHouseController 
{
	public static void main(String[] args)
	{
		GreenHouseControls gc = new GreenHouseControls();
		
		gc.addEvent(gc.new Bell(500000));
		gc.addEvent(gc.new LightOn(999000000/2));
		gc.addEvent(gc.new LightOff(999000000));

		gc.run();		
	}
	
}

Submit "Using of Inner Classes" to Facebook Submit "Using of Inner Classes" to Digg Submit "Using of Inner Classes" to del.icio.us Submit "Using of Inner Classes" to StumbleUpon Submit "Using of Inner Classes" to Google

Tags: None Add / Edit Tags
Categories
Uncategorized

Comments