1.装饰模式
package designPattern;
/**
* 装饰模式
* 装饰模式在不改变原有类结构的情况下向现有对象添加新功能
* 使用一个会变颜色的圆圈来举例
*/
public class DecoratingMode {
public static void main(String[] args) {
Shape circle = new Circle();
Shape square = new Square();
ColorDecorator colorDecorator = new ColorDecorator(circle);
colorDecorator.draw();
ColorDecorator colorDecorator1 = new ColorDecorator(square);
colorDecorator1.draw();
}
}
/**
* 形状接口
*/
interface Shape {
void print();
}
class Circle implements Shape {
@Override
public void print() {
System.out.println("i am circle");
}
}
class Square implements Shape {
@Override
public void print() {
System.out.println("i am square");
}
}
/**
* 装饰器抽象类
*/
abstract class AbstractDecorator {
protected Shape shape;
public abstract void draw();
}
/**
* 为形状装饰蓝色的装饰器
*/
class ColorDecorator extends AbstractDecorator {
public ColorDecorator(Shape shape) {
this.shape = shape;
}
@Override
public void draw() {
shape.print();
setColor();
}
public void setColor() {
System.out.println("Color is Blue");
}
}
2.外观模式
package designPattern;
/**
* 外观模式
* 外观模式(Facade Pattern)隐藏系统的复杂性,并向客户端提供了一个客户端可以访问系统的接口
*/
public class AppearanceMode {
public static void main(String[] args) {
OperationInterface operationInterface = new OperationInterface();
operationInterface.printCircle();
operationInterface.printSquare();
}
}
/**
* 形状接口
*/
interface Shape {
void print();
}
class Circle implements Shape {
@Override
public void print() {
System.out.println("i am circle");
}
}
class Square implements Shape {
@Override
public void print() {
System.out.println("i am square");
}
}
/**
* 包装类,隐藏内部结构,向用户提供使用接口
*/
class OperationInterface {
private Shape circle;
private Shape square;
public OperationInterface() {
circle = new Circle();
square = new Square();
}
public void printCircle() {
circle.print();
}
public void printSquare() {
square.print();
}
}
3.代理模式
package designPattern;
/**
* 代理模式
* 在代理模式(Proxy Pattern)中,一个类代表另一个类的功能。这种类型的设计模式属于结构型模式。
* 在代理模式中,我们创建具有现有对象的对象,以便向外界提供功能接口
*/
public class ProxyPattern {
public static void main(String[] args) {
ProxyImage proxyImage = new ProxyImage("test.jpg");
//第一次显示需要加载图片
proxyImage.display();
//第二次不需要加载
proxyImage.display();
}
}
/**
* 图像接口
*/
interface Image {
void display();
}
/**
* 真实的照片类
*/
class RealImage implements Image {
private String fileName;
public RealImage(String fileName) {
this.fileName = fileName;
loadFromDisk(fileName);
}
@Override
public void display() {
System.out.println("Displaying " + fileName);
}
private void loadFromDisk(String fileName) {
System.out.println("Loading " + fileName);
}
}
/**
* 代理照片类
*/
class ProxyImage implements Image {
private RealImage realImage;
private String fileName;
public ProxyImage(String fileName) {
this.fileName = fileName;
}
@Override
public void display() {
if (realImage == null) {
realImage = new RealImage(fileName);
}
realImage.display();
}
}