没什么多余的话,代码演示,简单粗暴
,借鉴的地方都附上了参考链接(做个优秀的搬运工),没附上的是自己总结的。如果相关例子写的有什么不准确,麻烦在评论里面指出来,最好附上代码,我会尽快修改文章中的相关实例
。设计原则名称 | 定 义 |
---|---|
单一职责原则(Single Responsibility Principle, SRP) | 一个类只负责一个功能领域中的相应职责 |
开闭原则(Open-Closed Principle, OCP) | 软件实体应对扩展开放,而对修改关闭 |
里氏代换原则(Liskov Substitution Principle, LSP) | 所有引用基类对象的地方能够透明地使用其子类的对象 |
迪米特法则(Law of Demeter, LoD) | 一个软件实体应当尽可能少地与其他实体发生相互作用 |
接口隔离原则(Interface Segregation Principle, ISP) | 使用多个专门的接口,而不使用单一的总接口 |
依赖倒转原则(Dependence Inversion Principle, DIP) | 抽象不应该依赖于细节,细节应该依赖于抽象 |
合成复用原则(Composite Reuse Principle, CRP) | 尽量使用对象组合,而不是继承来达到复用的目的 |
定义:一个类只有一个引起它变化的原因。
理解:对功能进行分类,代码进行解耦,一个类只管一件事
举例:就比如一个网络请求框架大体分为:请求类,缓存类,配置类,不能把这3个混在一起,必须分为3个类去实现不同的功能。
定义:一个实体(类、函数、模块等)应该对外扩展开放,对内修改关闭
理解:每次发生变化时,要通过新增代码来增强现有类型的行为,而不是修改原有代码。
举例:就比如在软件的生命周期内,因为产品迭代,软件升级维护等原因,需要对原有代码进行修改时,可能会给原有代码引入错误,也可能使得我们对整个功能不得不进行重构,并且需要对原有代码进行重新测试,这样的话,对开发周期影响很大,所以开闭原则刚好解决这个问题。
定义:继承必须确保父类所拥有的性质在子类中仍然成立。
理解:在继承类时,除了扩展一些新的功能之外,尽量不要删除或者修改对父类方法的引用,也尽量不要重写父类的方法。
举例:你看啊,就比如Object有个方法,叫equals,如果不遵守里氏代替原则,它的子类重写了equals这个方法,并且返回了个null,这个子类的下一个继承者也会返回null,那么,在不同开发人员开发时,可能考虑不到这个问题,那么就可能导致程序崩溃。
定义:一个模块或对象应尽量少的与其他实体之间发生相互作用,使得系统功能模块相对独立,这样当一个模块修改时,影响的模块就会越少,扩展起来更加容易。
理解:一个对象应该对其他对象有最少的了解;一个类应该对自己需要耦合或调用的类知道得最少,类的内部如何实现、如何复杂都与调用者或者依赖者没关系,调用者或者依赖者只需要知道他需要的方法即可,其他的一概不关心。类与类之间的关系越密切,耦合度越大,当一个类发生改变时,对另一个类的影响也越大。
举例:一般在使用框架的时候,框架的开发者会抽出一个类供外部调用,而这个主要的类像是一个中介一样去调用框架里面的其他类,恰恰框架里面其他类一般都是不可访问(调用)的,这个框架就遵守了迪米特原则,其他开发人员只关心调用的方法,并不需要关心功能具体如何实现。
定义:使用多个专门功能的接口,而不是使用单一的总接口
理解:在定义接口方法时应该合理化,尽量追求简单最小,避免接口臃肿
举例:在实际开发中,往往为了节省时间,可能会将多个功能的方法抽成一个接口,其实这设计理念不正确的,这样会使接口处于臃肿的状态,这时就需要合理的拆分接口中的方法,另外抽取成一个独立的接口,避免原有的接口臃肿导致代码理解困难。
定义:细节应该依赖于抽象,而抽象不应该依赖于细节
理解:高层模块不依赖低层次模块的细节,不依赖具体的类,而是依赖于接口
举例:比如说我们写一个网络框架,为了满足不同开发者的需求,即能使用高效的OkHttp框架,也可以使用原生的API。那么是如何进行切换的呢,这个时候需要面向接口编程思想了,把一些网络请求的方法封装成一个接口,然后分别创建OkHttp和原生API的接口实现类,当然也可以扩展其他网络框架的应用。
定义:尽量使用对象组合,而不是继承来达到复用的目的。
理解:它要求在软件复用时,要尽量先使用组合或者聚合等关联关系来实现,其次才考虑使用继承关系来实现。
举例:相当于我们开发软件,一个模块的构造,就像搭积木一样,通过组合的形式,完成整体的构建;现在声明式UI框架,对于这种思想比较贯彻。
参考
饿汉模式
public class Singleton {
// 只会实例化一次
private static Singleton instance = new Singleton();
// 私有构造方法,防止被实例化
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
懒汉模式
public class Singleton {
// 持有私有静态实例,防止被引用;赋值为null,目的是实现延迟加载;volatile修饰是禁止重排
private volatile static Singleton instance = null;
// 私有构造方法,防止被实例化
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (instance) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
静态内部类模式
public class Singleton {
// 私有构造方法,防止被实例化
private Singleton() {}
// 获取实例
public static Singleton getInstance() {
return Inner.instance;
}
// 使用一个内部类来维护单例,只有在该类被加载的时候,才会实例化对象
private static class Inner {
private static Singleton instance = new Singleton();
}
}
枚举模式
public enum Singleton {
// 创建一个枚举对象,该对象天生为单例
INSTANCE;
public Singleton getInstance(){
return INSTANCE;
}
}
参考
public interface Phone {
//实施开机操作的时候,返回手机系统
String startUp();
}
public class AndroidPhone implements Phone {
@Override
public String startUp() {
return "Android";
}
}
public class IOSPhone implements Phone {
@Override
public String startUp() {
return "IOS";
}
}
public class PhoneFactory {
private static Phone mPhone;
//根据系统关键字获取相应手机对象
public static Phone createPhone(String system) {
switch (system) {
case "Android":
mPhone = new AndroidPhone();
break;
case "IOS":
mPhone = new IOSPhone();
break;
}
return mPhone;
}
}
public void test() {
Phone android = PhoneFactory.createPhone("Android");
Phone ios = PhoneFactory.createPhone("IOS");
System.out.print(android.startUp() + "\n");
System.out.print(ios.startUp() + "\n");
}
public interface PhoneFactory {
//获取相关手机实例
Phone getPhone();
}
public class AndroidPhoneFactory implements PhoneFactory {
@Override
public Phone getPhone() {
return new AndroidPhone();
}
}
public class IOSPhoneFactory implements PhoneFactory {
@Override
public Phone getPhone() {
return new IOSPhone();
}
}
public void test() {
PhoneFactory androidMiFactory = new AndroidPhoneFactory();
PhoneFactory iosFactory = new IOSPhoneFactory();
System.out.print(androidFactory.getPhone().startUp() + "\n");
System.out.print(iosFactory.getPhone().startUp() + "\n");
}
1、第一种方式
public interface PhoneSystem {
//获取Android手机实例
Phone getAndroid();
//获取IOS手机实例
Phone getIOS();
}
public class PhoneFactory implements PhoneSystem {
@Override
public Phone getAndroid() {
return new AndroidPhone();
}
@Override
public Phone getIOS() {
return new IOSPhone();
}
}
public void test() {
PhoneSystem phoneSystem = new PhoneFactory();
Phone android = phoneSystem.getXiaoMi();
Phone ios = phoneSystem.getHuaWei();
System.out.print(android.startUp() + "\n");
System.out.print(ios.startUp() + "\n");
}
2、第二种方式
public class PhoneFactory {
private static Phone instance;
//模拟个数据
private String SYSTEM = "IOS";
public static Phone getInstance() {
if("Android".equals(SYSTEM))
{
return new AndroidPhone();
}
if("IOS".equals(SYSTEM))
{
return new IOSPhone();
}
return null;
}
}
public static void test() {
Phone phone = PhoneFactory.getInstance();
if (phone == null)
return;
System.out.print(phone.startUp() + "\n");
}
说明
实现
public class Computer {
private final String cpu;//必须
private final String ram;//必须
private final int usbCount;//可选
private final String keyboard;//可选
private final String display;//可选
private Computer(Builder builder){
this.cpu=builder.cpu;
this.ram=builder.ram;
this.usbCount=builder.usbCount;
this.keyboard=builder.keyboard;
this.display=builder.display;
}
public static class Builder{
private String cpu;//必须
private String ram;//必须
private int usbCount;//可选
private String keyboard;//可选
private String display;//可选
public Builder(String cup,String ram){
this.cpu=cup;
this.ram=ram;
}
public Builder setUsbCount(int usbCount) {
this.usbCount = usbCount;
return this;
}
public Builder setKeyboard(String keyboard) {
this.keyboard = keyboard;
return this;
}
public Builder setDisplay(String display) {
this.display = display;
return this;
}
public Computer build(){
return new Computer(this);
}
}
}
使用
Computer computer = new Computer.Builder("因特尔","三星")
.setDisplay("三星24寸")
.setKeyboard("罗技")
.setUsbCount(2)
.build();
参考
定义
实现
public class Prototype implements Cloneable, Serializable {
private static final long serialVersionUID = 1L;
private String string;
private SerializableObject obj;
// 浅复制
public Object clone() throws CloneNotSupportedException {
Prototype proto = (Prototype) super.clone();
return proto;
}
// 深复制
public Object deepClone() throws IOException, ClassNotFoundException {
// 写入当前对象的二进制流
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
// 读出二进制流产生的新对象
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return ois.readObject();
}
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
public SerializableObject getObj() {
return obj;
}
public void setObj(SerializableObject obj) {
this.obj = obj;
}
}
class SerializableObject implements Serializable {
private static final long serialVersionUID = 1L;
}
参考
public class Adaptee {
public void adapteeRequest() {
System.out.println("被适配者的方法");
}
}
public interface Target {
void request();
}
public class Adapter extends Adaptee implements Target{
@Override
public void request() {
System.out.println("concreteTarget目标方法");
super.adapteeRequest();
}
}
public class Test {
public static void main(String[] args) {
Target adapterTarget = new Adapter();
adapterTarget.request();
}
}
concreteTarget目标方法
被适配者的方法
public interface AC {
int outputAC();
}
public class AC220 implements AC {
public final int output = 220;
@Override
public int outputAC() {
return output;
}
}
public interface DC5Adapter {
int outputDC5V(AC ac);
}
public class PowerAdapter implements DC5Adapter {
public static final int voltage = 220;
@Override
public int outputDC5V(AC ac) {
int adapterInput = ac.outputAC();
//变压器...
int adapterOutput = adapterInput / 44;
System.out.println("使用PowerAdapter变压适配器,输入AC:" + adapterInput + "V"
+ ",输出DC:" + adapterOutput + "V");
return adapterOutput;
}
}
public class Test {
private List<DC5Adapter> adapters = new LinkedList<DC5Adapter>();
public static void main(String[] args) {
AC ac = new AC220(); //实例化220v对象
DC5Adapter adapter = new PowerAdapter(); //实例化适配器
adapter.outputDC5V(ac);
}
}
使用PowerAdapter变压适配器,输入AC:220V,输出DC:5V
public interface Sourceable {
public void method1();
public void method2();
}
public abstract class Wrapper implements Sourceable{
public void method1(){}
public void method2(){}
}
public class SourceSub extends Wrapper {
@Override
public void method1(){
System.out.println("实现方法一");
}
}
参考
定义
实现
public interface Shape {
void draw();
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Shape: Rectangle");
}
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Shape: Circle");
}
}
public abstract class ShapeDecorator implements Shape {
protected Shape decoratedShape;
public ShapeDecorator(Shape decoratedShape){
this.decoratedShape = decoratedShape;
}
@Override
public void draw(){
decoratedShape.draw();
System.out.println("Border Color: Red");
}
}
public class Test {
public static void main(String[] args) {
Shape circle = new Circle();
ShapeDecorator circleShape = new ShapeDecorator(new Circle());
ShapeDecorator rectangleShape = new ShapeDecorator(new Rectangle());
System.out.println("Circle with normal border");
circle.draw();
System.out.println("\nCircle of red border");
circleShape.draw();
System.out.println("\nRectangle of red border");
rectangleShape.draw();
}
}
Circle with normal border
Shape: Circle
Circle of red border
Shape: Circle
Border Color: Red
Rectangle of red border
Shape: Rectangle
Border Color: Red
参考
定义
实现
public interface Shape {
void draw();
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Shape: Circle");
}
}
public class ProxyShape implements Shape {
private Circle circle;
@Override
public void draw() {
if(circle == null){
circle = new Circle();
}
circle.draw();
}
}
public class Test {
public static void main(String[] args) {
Shape shapeProxy = new ProxyShape();
shape.draw();
}
}
Shape: Circle
参考
定义
实现
public class CPU {
public void startup(){
System.out.println("cpu startup!");
}
public void shutdown(){
System.out.println("cpu shutdown!");
}
}
public class Memory {
public void startup(){
System.out.println("memory startup!");
}
public void shutdown(){
System.out.println("memory shutdown!");
}
}
public class Disk {
public void startup(){
System.out.println("disk startup!");
}
public void shutdown(){
System.out.println("disk shutdown!");
}
}
public class Computer {
private CPU cpu;
private Memory memory;
private Disk disk;
public Computer(){
cpu = new CPU();
memory = new Memory();
disk = new Disk();
}
public void startup(){
cpu.startup();
memory.startup();
disk.startup();
}
public void shutdown(){
cpu.shutdown();
memory.shutdown();
disk.shutdown();
}
}
public class Test {
public static void main(String[] args) {
Computer computer = new Computer();
computer.startup();
computer.shutdown();
}
}
cpu startup!
memory startup!
disk startup!
cpu shutdown!
memory shutdown!
disk shutdown!
参考
定义
实现
第一个维度
public interface DrawAPI {
public void drawColor();
}
public class RedDraw implements DrawAPI {
@Override
public void drawColor() {
System.out.println("color: red");
}
}
public class GreenDraw implements DrawAPI {
@Override
public void drawColor() {
System.out.println("color: green");
}
}
第二个维度
public abstract class Shape {
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI){
this.drawAPI = drawAPI;
}
public abstract void draw();
}
public class Circle extends Shape {
public Circle(DrawAPI drawAPI) {
super(drawAPI);
}
public void draw() {
System.out.println("Drawing Circle");
drawAPI.drawColor();
}
}
public class Rectangle extends Shape {
public Rectangle(DrawAPI drawAPI) {
super(drawAPI);
}
public void draw() {
System.out.println("Drawing Rectangle");
drawAPI.drawColor();
}
}
public class BridgeDemo {
public static void main(String[] args) {
Shape redCircle = new Circle(new RedDraw());
Shape greenRectangle = new Rectangle(new GreenDraw());
redCircle.draw();
greenRectangle.draw();
}
}
Drawing Circle
color: red
Drawing Rectangle
color: green
定义
实现
abstract class Component {
public abstract void operation();
public void add(Component c) {
throw new UnsupportedOperationException();
}
public void remove(Component c) {
throw new UnsupportedOperationException();
}
}
class ConcreteComponent1 extends Component {
public void operation() {
System.out.println("operation of concrete component 1 ");
}
}
class ConcreteComponent2 extends Component {
public void operation() {
System.out.println("operation of concrete component 2 ");
}
}
class ConcreteComponent3 extends Component {
public void operation() {
System.out.println("operation of concrete component 3 ");
}
}
class Composite extends Component {
private ArrayList<Component> children;
public Composite() {
children = new ArrayList<Component>();
}
public void operation() {
for(Component child: children) {
child.operation();
}
}
public void add(Component c) {
children.add(c);
}
public void remove(Component c) {
children.remove(c);
}
}
public class Client {
public static void main(String[] args) {
Component c1 = new ConcreteComponent1();
Component c2 = new ConcreteComponent2();
Component c3 = new ConcreteComponent3();
Component c = new Composite();
c.add(c1);
c.add(c2);
c.add(c3);
c.operation();
c.remove(c2);
c.operation();
}
}
参考
定义
class Flyweight {
//内部状态innerState作为成员变量,同一个享元对象其内部状态是一致的
private String innerState;
public Flyweight(String innerState) {
this.innerState = innerState;
}
//外部状态outerState在使用时由外部设置,不保存在享元对象中,即使是同一个对象
public void operation(String outerState) {
//......
}
}
class FlyweightFactory {
//定义一个HashMap用于存储享元对象,实现享元池
private HashMap flyweights = newHashMap();
public Flyweight getFlyweight(String key){
//如果对象存在,则直接从享元池获取
if(flyWeights.containsKey(key)){
return (Flyweight) flyweights.get(key);
} else {
//如果对象不存在,先创建一个新的对象添加到享元池中,然后返回
Flyweight fw = newConcreteFlyweight();
flyweights.put(key,fw);
return fw;
}
}
}
/**
* 经典享元模式方法
* 场景:解决某些场景频繁生成实例问题;使用泛型,节省写判断逻辑
* 使用:String s = classicFlyweight(String.class);
*/
private Map<String, Object> flyweightMap;
private <T> T classicFlyweight(Class<T> clazz) {
T t;
if (flyweightMap == null)
flyweightMap = new HashMap<>();
String key = clazz.getName();
if (flyweightMap.get(key) != null) {
t = (T) flyweightMap.get(key);
}else {
try {
t = clazz.newInstance();
flyweightMap.put(key, t);
} catch (Exception e) {
t = null;
}
}
return t;
}
public class ConnectionPool {
private Vector<Connection> pool;
//公有属性
private String url = "jdbc:mysql://localhost:3306/test";
private String username = "root";
private String password = "root";
private String driverClassName = "com.mysql.jdbc.Driver";
private int poolSize = 100;
private static ConnectionPool instance = null;
Connection conn = null;
//构造方法,做一些初始化工作
private ConnectionPool() {
pool = new Vector<Connection>(poolSize);
for (int i = 0; i < poolSize; i++) {
try {
Class.forName(driverClassName);
conn = DriverManager.getConnection(url, username, password);
pool.add(conn);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//返回连接到连接池
public synchronized void release() {
pool.add(conn);
}
//返回连接池中的一个数据库连接
public synchronized Connection getConnection() {
if (pool.size() > 0) {
Connection conn = pool.get(0);
pool.remove(conn);
return conn;
} else {
return null;
}
}
}
参考
相同点
不同点
定义
实现
public interface Expression {
public boolean interpret(String context);
}
public class TerminalExpression implements Expression {
private String data;
public TerminalExpression(String data){
this.data = data;
}
@Override
public boolean interpret(String context) {
if(context.contains(data)){
return true;
}
return false;
}
}
public class OrExpression implements Expression {
private Expression expr1 = null;
private Expression expr2 = null;
public OrExpression(Expression expr1, Expression expr2) {
this.expr1 = expr1;
this.expr2 = expr2;
}
@Override
public boolean interpret(String context) {
return expr1.interpret(context) || expr2.interpret(context);
}
}
public class AndExpression implements Expression {
private Expression expr1 = null;
private Expression expr2 = null;
public AndExpression(Expression expr1, Expression expr2) {
this.expr1 = expr1;
this.expr2 = expr2;
}
@Override
public boolean interpret(String context) {
return expr1.interpret(context) && expr2.interpret(context);
}
}
public class Test {
//规则:Robert 和 John 是男性
public static Expression getMaleExpression(){
Expression robert = new TerminalExpression("John");
Expression john = new TerminalExpression("male");
return new OrExpression(robert, john);
}
//规则:Julie 是一个已婚的女性
public static Expression getMarriedWomanExpression(){
Expression julie = new TerminalExpression("Julie");
Expression married = new TerminalExpression("Married");
return new AndExpression(julie, married);
}
public static void main(String[] args) {
Expression isMale = getMaleExpression();
Expression isMarriedWoman = getMarriedWomanExpression();
System.out.println("John is male? " + isMale.interpret("John"));
System.out.println("Julie is a married women? "
+ isMarriedWoman.interpret("Married Julie"));
}
}
John is male? true
Julie is a married women? true
参考
定义
实现
public interface State {
public void doAction(Context context);
}
public class StartState implements State {
public void doAction(Context context) {
System.out.println("Player is in start state");
context.setState(this);
}
public String toString(){
return "Start State";
}
}
public class StopState implements State {
public void doAction(Context context) {
System.out.println("Player is in stop state");
context.setState(this);
}
public String toString(){
return "Stop State";
}
}
public class Context {
private State state;
public Context(){
state = null;
}
public void setState(State state){
this.state = state;
}
public State getState(){
return state;
}
}
public class StatePatternDemo {
public static void main(String[] args) {
Context context = new Context();
StartState startState = new StartState();
startState.doAction(context);
System.out.println(context.getState().toString());
StopState stopState = new StopState();
stopState.doAction(context);
System.out.println(context.getState().toString());
}
}
Player is in start state
Start State
Player is in stop state
Stop State
参考
定义
实现
public interface Strategy {
int calculate(int a, int b);
}
// 加法算法
public class AddStrategy implements Strategy{
@Override
public int calculate(int a, int b) {
return a + b;
}
}
// 减法算法
public class SubtractStrategy implements Strategy{
@Override
public int calculate(int a, int b) {
return a - b;
}
}
public class Test{
public static void main(String[] args) {
Strategy strategy = new AddStrategy();
// 输出3
System.out.println(strategy.calculate(1, 2));
// 动态替换算法(策略)
strategy = new SubtractStrategy();
// 输出-1
System.out.println(strategy.calculate(1, 2));
}
}
参考
定义
实现
public interface Observer {
//更新内容
public void update(String msg);
}
public class TestObserver implements Observer{
private String info;
public TestObserver(String info){
this.info = info;
}
@Override
public void update(String msg) {
System.out.println(info + "----" + msg);
}
}
public class TestSubject {
private List<Observer> mList = new ArrayList();
//添加观察者
public void attach(Observer observer) {
mList.add(observer);
}
//删除观察者
public void detach(Observer observer) {
mList.remove(observer);
}
//通知更新
public void notify(String msg) {
for (Observer observer : mList) {
observer.update(msg);
}
}
}
public class TestMain {
public static void main(String[] args) {
Subject subject = new TestSubject();
Observer observerA = new TestObserver("A:");
Observer observerB = new TestObserver("B:");
subject.attach(observerA);
subject.attach(observerB);
subject.notify("通知One");
subject.detach(observerA);
subject.notify("通知Two");
}
}
定义
实现
public interface Mediator {
public void showMessage(String msg);
}
public class User implements Mediator{
@Override
public void showMessage(String message){
System.out.println("User: " + message);
}
}
public class ChatRoom implements Mediator{
@Override
public void showMessage(String message){
(new User()).showMessage(message);
}
}
public class Test {
public static void main(String[] args) {
ChatRoom John = new ChatRoom();
John.showMessage("Hi! John!");
}
}
User: Hi! John!
定义
实现
public class Original {
public String value;
public Original(String value) {
this.value = value;
}
public Memento createMemento(){
return new Memento(value);
}
public void restoreMemento(Memento memento){
this.value = memento.value;
}
}
public class Memento {
public String value;
public Memento(String value) {
this.value = value;
}
}
public class Storage {
public Memento memento;
public Storage(Memento memento) {
this.memento = memento;
}
}
public class Test {
public static void main(String[] args) {
// 创建原始类
Original origi = new Original("egg");
// 创建备忘录
Storage storage = new Storage(origi.createMemento());
// 修改原始类的状态
System.out.println("初始化状态为:" + origi.value);
System.out.println("修改后的状态为:" + origi.value = "niu");
// 回复原始类的状态
origi.restoreMemento(storage.memento);
System.out.println("恢复后的状态为:" + origi.value);
}
}
初始化状态为:egg
修改后的状态为:niu
恢复后的状态为:egg
参考
定义
实现
public interface Order {
public void execute();
}
public class BuyStock implements Order {
private String name = "ABC";
private int quantity = 10;
@Override
public void execute() {
System.out.println("Stock [ Name: "+name+", Quantity: " + quantity +" ] bought");
}
}
public class Broker {
private List<Order> orderList = new ArrayList<Order>();
public void takeOrder(Order order){
orderList.add(order);
}
public void placeOrders(){
for (Order order : orderList) {
order.execute();
}
orderList.clear();
}
}
public class CommandPatternDemo {
public static void main(String[] args) {
Stock abcStock = new Stock();
BuyStock buyStockOrder = new BuyStock(abcStock);
Broker broker = new Broker();
broker.takeOrder(buyStockOrder);
broker.placeOrders();
}
}
Stock [ Name: ABC, Quantity: 10 ] bought
参考
定义
责任链会将特定行为转换为被称作处理者的独立对象。 每个检查步骤都可被抽取为仅有单个方法的类, 并执行检查操作。 请求及其数据则会被作为参数传递给该方法。
该模式建议你将这些处理者连成一条链。 链上的每个处理者都有一个成员变量来保存对于下一处理者的引用。 除了处理请求外, 处理者还负责沿着链传递请求。 请求会在链上移动, 直至所有处理者都有机会对其进行处理。
最重要的是: 处理者可以决定不再沿着链传递请求, 这可高效地取消所有后续处理步骤。
实现
public abstract class AbstractLogger {
public static int INFO = 1;
public static int DEBUG = 2;
public static int ERROR = 3;
protected int level;
//责任链中的下一个元素
protected AbstractLogger nextLogger;
public void setNextLogger(AbstractLogger nextLogger){
this.nextLogger = nextLogger;
}
public void logMessage(int level, String message){
if(this.level <= level){
write(message);
}
if(nextLogger != null){
nextLogger.logMessage(level, message);
}
}
abstract protected void write(String message);
}
public class ConsoleLogger extends AbstractLogger {
public ConsoleLogger(int level){
this.level = level;
}
@Override
protected void write(String message) {
System.out.println("Standard Console::Logger: " + message);
}
}
public class ErrorLogger extends AbstractLogger {
public ErrorLogger(int level){
this.level = level;
}
@Override
protected void write(String message) {
System.out.println("Error Console::Logger: " + message);
}
}
public class FileLogger extends AbstractLogger {
public FileLogger(int level){
this.level = level;
}
@Override
protected void write(String message) {
System.out.println("File::Logger: " + message);
}
}
public class Test {
private static AbstractLogger getChainOfLoggers(){
AbstractLogger errorLogger = new ErrorLogger(AbstractLogger.ERROR);
AbstractLogger fileLogger = new FileLogger(AbstractLogger.DEBUG);
AbstractLogger consoleLogger = new ConsoleLogger(AbstractLogger.INFO);
errorLogger.setNextLogger(fileLogger);
fileLogger.setNextLogger(consoleLogger);
return errorLogger;
}
public static void main(String[] args) {
AbstractLogger loggerChain = getChainOfLoggers();
loggerChain.logMessage(AbstractLogger.INFO, "This is an information.");
loggerChain.logMessage(AbstractLogger.DEBUG, "This is a debug level information.");
loggerChain.logMessage(AbstractLogger.ERROR, "This is an error information.");
}
}
Standard Console::Logger: This is an information.
File::Logger: This is a debug level information.
Standard Console::Logger: This is a debug level information.
Error Console::Logger: This is an error information.
File::Logger: This is an error information.
Standard Console::Logger: This is an error information.
参考
定义
实现
public interface Visitor {
public void visit(Subject sub);
}
public class MyVisitor implements Visitor {
@Override
public void visit(Subject sub) {
System.out.println("visit the subject:"+sub.getSubject());
}
}
public interface Subject {
public void accept(Visitor visitor);
public String getSubject();
}
public class MySubject implements Subject {
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
@Override
public String getSubject() {
return "love";
}
}
public class Test {
public static void main(String[] args) {
Visitor visitor = new MyVisitor();
Subject sub = new MySubject();
sub.accept(visitor);
}
}
参考
定义
实现
public interface Iterator {
public boolean hasNext();
public Object next();
}
public interface Container {
public Iterator getIterator();
}
public class NameRepository implements Container {
public String names[] = {"Robert" , "John" ,"Julie" , "Lora"};
@Override
public Iterator getIterator() {
return new NameIterator();
}
private class NameIterator implements Iterator {
int index;
@Override
public boolean hasNext() {
if(index < names.length){
return true;
}
return false;
}
@Override
public Object next() {
if(this.hasNext()){
return names[index++];
}
return null;
}
}
}
public class Test {
public static void main(String[] args) {
NameRepository namesRepository = new NameRepository();
for(Iterator iter = namesRepository.getIterator(); iter.hasNext();){
String name = (String)iter.next();
System.out.println("Name : " + name);
}
}
}
Name : Robert
Name : John
Name : Julie
Name : Lora
参考
定义
实现
public abstract class Game {
abstract void initialize();
abstract void startPlay();
abstract void endPlay();
//模板
public final void play(){
//初始化游戏
initialize();
//开始游戏
startPlay();
//结束游戏
endPlay();
}
}
public class Football extends Game {
@Override
void endPlay() {
System.out.println("Football Game Finished!");
}
@Override
void initialize() {
System.out.println("Football Game Initialized! Start playing.");
}
@Override
void startPlay() {
System.out.println("Football Game Started. Enjoy the game!");
}
}
public class Test {
public static void main(String[] args) {
Game game = new Football();
game.play();
}
}
Football Game Initialized! Start playing.
Football Game Started. Enjoy the game!
Football Game Finished!
参考
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。