import java.util.*;
import java.lang.*;
import java.io.*;
interface Shape
{
void draw ();
}
class Rectangle implements Shape
{
public void draw () {
System.out.println("A rectangle");
}
}
class Circle implements Shape
{
public void draw () {
System.out.println("A circle");
}
}
abstract class ShapeDecorator implements Shape
{
protected Shape decoratedShape;
public ShapeDecorator (Shape s) {
this.decoratedShape = s;
}
public void draw (){
decoratedShape.draw();
}
}
class RedShapeDecorator extends ShapeDecorator
{
public RedShapeDecorator (Shape s) {
super(s);
}
@Override
public void draw() {
decoratedShape.draw();
setRedBorder(decoratedShape);
}
private void setRedBorder (Shape s) {
System.out.println("Red Border");
}
}
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Shape circle = new Circle();
Shape rectangle = new Rectangle();
Shape redCircle = new RedShapeDecorator (new Circle());
Shape redRectangle = new RedShapeDecorator (new Rectangle ());
circle.draw();
redCircle.draw();
redRectangle.draw();
}
}
Code borrowed from
http://www.tutorialspoint.com/
import java.lang.*;
import java.io.*;
interface Shape
{
void draw ();
}
class Rectangle implements Shape
{
public void draw () {
System.out.println("A rectangle");
}
}
class Circle implements Shape
{
public void draw () {
System.out.println("A circle");
}
}
abstract class ShapeDecorator implements Shape
{
protected Shape decoratedShape;
public ShapeDecorator (Shape s) {
this.decoratedShape = s;
}
public void draw (){
decoratedShape.draw();
}
}
class RedShapeDecorator extends ShapeDecorator
{
public RedShapeDecorator (Shape s) {
super(s);
}
@Override
public void draw() {
decoratedShape.draw();
setRedBorder(decoratedShape);
}
private void setRedBorder (Shape s) {
System.out.println("Red Border");
}
}
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Shape circle = new Circle();
Shape rectangle = new Rectangle();
Shape redCircle = new RedShapeDecorator (new Circle());
Shape redRectangle = new RedShapeDecorator (new Rectangle ());
circle.draw();
redCircle.draw();
redRectangle.draw();
}
}
http://www.tutorialspoint.com/
No comments:
Post a Comment