JAVA设计模式
代码参考https://gitee.com/wangbo188/design
注意:参考
原文出自【易百教程】,商业转载请联系作者获得授权,非商业请保留原文链接:https://www.yiibai.com/design_pattern/singleton_pattern.html
1、工厂模式
工厂模式定义 : 提供创建对象的接口.
//对象的属性行为创建
public interface Shape {
void draw();
}
public class Rectangle implements Shape{
@Override
public void draw() {
System.out.println("Rectangle...-----Rectangle");
}
}
public class Circle implements Shape{
@Override
public void draw() {
System.out.println("Circle...--Circle");
}
}
public class Square implements Shape{
@Override
public void draw() {
System.out.println("Square...--Square");
}
}
//创建工厂获取对应条件的对象
public class ShapeFactory {
//根据类型获取不同对象
public Shape getShape(String shapeType) {
if (shapeType == null || "".equals(shapeType)) {
return null;
}
if ("circle".equals(shapeType)) {
return new Circle();
}
if ("rectangle".equals(shapeType)) {
return new Rectangle();
}
if ("square".equals(shapeType)) {
return new Square();
}
return null;
}
}
public class Demo {
//工厂模式,按需从工厂得到需要的对象
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Shape circle = shapeFactory.getShape("circle");
circle.draw();//Circle...--Circle
Shape rectangle = shapeFactory.getShape("rectangle");
rectangle.draw();//Rectangle...-----Rectangle
Shape square = shapeFactory.getShape("square");
square.draw();//Square...--Square
}
}
2、抽象工厂模式
public interface Shape {
void draw();
}
public class Circle implements Shape{
@Override
public void draw() {
System.out.println("Circle...");
}
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Rectangle...");
}
}
public interface Color {
void fill();
}
public class Blue implements Color {
@Override
public void fill() {
System.out.println("Blue...");
}
}
public class Green implements Color {
@Override
public void fill() {
System.out.println("Green...");
}
}
/**
* 抽象工厂,统一封装装载对象作用
*/
public abstract class AbstractFactory {
public abstract Color getColor(String color);
public abstract Shape getShape(String shape);
}
public class ShapeFactory extends AbstractFactory {
@Override
public Color getColor(String color) {
return null;
}
@Override
public Shape getShape(String shape) {
if (shape == null || "".equals(shape)) {
return null;
}
if ("circle".equals(shape)) {
return new Circle();
}
if ("rectangle".equals(shape)) {
return new Rectangle();
}
return null;
}
}
public class ColorFactory extends AbstractFactory {
@Override
public Color getColor(String color) {
if (color == null || "".equals(color)) {
return null;
}
if ("blue".equals(color)) {
return new Blue();
}
if ("red".equals(color)) {
return new Red();
}
if ("green".equals(color)) {
return new Green();
}
return null;
}
@Override
public Shape getShape(String shape) {
return null;
}
}
/**
* 选择调用工厂的生产器
*/
public class FactoryProducer {
public static AbstractFactory getFactory(String choice) {
if ("shape".equals(choice)) {
return new ShapeFactory();
}
if ("color".equals(choice)) {
return new ColorFactory();
}
return null;
}
}
/**
* 通过调用抽象工厂的生产器去调用工厂
* 根据需要的对象属性条件获取对象
*/
public class Demo {
public static void main(String[] args) {
AbstractFactory shape = FactoryProducer.getFactory("shape");
Shape circle = shape.getShape("circle");
circle.draw();//Circle...
AbstractFactory color = FactoryProducer.getFactory("color");
Color red = color.getColor("red");
red.fill();//red...
}
}
3、单例模式
/**
* 单例对象
*/
public class SingleObject {
private SingleObject() {
}
//事先创建好单例的对象,随着类的加载只会更新一次
private static SingleObject singleObject = new SingleObject();
/**
* 直接获取对象,即每次对象都是一致的
* 随着类的加载只会更新一次
* @return
*/
public static SingleObject getInstance() {
return singleObject;
}
}
public class Demo {
public static void main(String[] args) {
SingleObject instance = SingleObject.getInstance();
System.out.println(instance);//com.singleton.SingleObject@28d93b30
SingleObject instance1 = SingleObject.getInstance();
System.out.println(instance1);//com.singleton.SingleObject@28d93b30
//static获取的对象都是一样的 所以称为单例对象模式
}
}
4、建造者模式
对复杂的对象进行简单的创建,内部封装复杂的逻辑对象处理
基本对象结构:商品+打包方式
/**
* 商品
*
* @author wangbo
* @since 2022/5/5 14:18
*/
public interface Item {
String name();
Float price();
Packing pack();
}
/**
* 打包方式
*
* @author wangbo
* @since 2022/5/5 14:28
*/
public interface Packing {
String pack();
}
对打包方式的解释处理
/**
* 饮料瓶装
*
* @author wangbo
* @since 2022/5/5 14:32
*/
public class Bottle implements Packing{
@Override
public String pack() {
return "Bottle...";
}
}
/**
* 食品包装
*
* @author wangbo
* @since 2022/5/5 14:31
*/
public class Wrapper implements Packing{
@Override
public String pack() {
return "Wrapper...";
}
}
根据商品打包方式不同处理商品
/**
* 汉堡包食品
*
* @author wangbo
* @since 2022/5/5 14:35
*/
public abstract class Burger implements Item{
@Override
public Packing pack() {
return new Wrapper();
}
}
/**
* 冷饮
*
* @author wangbo
* @since 2022/5/5 14:37
*/
public abstract class ColdDrink implements Item{
@Override
public Packing pack() {
return new Bottle();
}
}
具体商品的实现
/**
* @author wangbo
* @since 2022/5/5 14:42
*/
public class ChickenBurger extends Burger{
@Override
public String name() {
return "ChickenBurger";
}
@Override
public Float price() {
return 11.0f;
}
}
/**
* @author wangbo
* @since 2022/5/5 14:40
*/
public class VegBurger extends Burger{
@Override
public String name() {
return "VegBurger";
}
@Override
public Float price() {
return 10.0f;
}
}
/**
* @author wangbo
* @since 2022/5/5 14:44
*/
public class Coke extends ColdDrink{
@Override
public String name() {
return "Coke";
}
@Override
public Float price() {
return 2.5f;
}
}
/**
* @author wangbo
* @since 2022/5/5 14:46
*/
public class Pepsi extends ColdDrink{
@Override
public String name() {
return "Pepsi";
}
@Override
public Float price() {
return 3f;
}
}
封装对象
/**
* 封装对象
*
* @author wangbo
* @since 2022/5/5 14:47
*/
public class Meal {
private List<Item> items = new ArrayList<>();
public void addItem(Item item) {
items.add(item);
}
public void showItem() {
items.stream().forEach(item -> {
System.out.println("name---"+item.name());
System.out.println("price---"+item.price());
System.out.println("pack---"+item.pack().pack());
});
}
}
具体对象细节构造
/**
* 构造器
* 对Meal进行构造对象 包含了具体的食品或者冷饮的细节对象
*
* @author wangbo
* @since 2022/5/5 14:56
*/
public class MealBuilder {
public Meal prepareVegMeal() {
Meal meal = new Meal();
meal.addItem(new VegBurger());
meal.addItem(new Coke());
return meal;
}
public Meal prepareNoVegMeal() {
Meal meal = new Meal();
meal.addItem(new ChickenBurger());
meal.addItem(new Pepsi());
return meal;
}
}
Demo
/**
* @author wangbo
* @since 2022/5/5 15:04
*/
public class Demo {
public static void main(String[] args) {
MealBuilder mealBuilder = new MealBuilder();
Meal meal = mealBuilder.prepareNoVegMeal();
meal.showItem();
System.out.println("--------------");
Meal meal1 = mealBuilder.prepareVegMeal();
meal1.showItem();
/**
* name---ChickenBurger
* price---11.0
* pack---Wrapper...
* name---Pepsi
* price---3.0
* pack---Bottle...
* --------------
* name---VegBurger
* price---10.0
* pack---Wrapper...
* name---Coke
* price---2.5
* pack---Bottle...
*/
}
}
5、原型模式
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象
java 的cloneable 实现的是浅拷贝 实际还是指向一个对象
/**
* abstract对象(之后获取的都是浅拷贝的对象)
*
* @author wangbo
* @since 2022/5/5 15:34
*/
public abstract class Shape implements Cloneable{
protected String type;
@Override
protected Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
/**
* @author wangbo
* @since 2022/5/5 15:39
*/
public class Circle extends Shape{
public Circle() {
this.type = "Circle";
}
}
/**
* @author wangbo
* @since 2022/5/5 15:41
*/
public class Rectangle extends Shape{
public Rectangle() {
type = "Rectangle";
}
}
/**
* 存放对象缓存的类
*
* @author wangbo
* @since 2022/5/5 15:42
*/
public class ShapeCache {
private static Map<Integer,Shape> map = new HashMap<>();
public static Shape getShape(Integer id) {
Shape shape = map.get(id);
return (Shape)shape.clone();
}
public static void loadShape() {
map.put(1, new Circle());
map.put(2,new Rectangle());
}
}
Demo
/**
* @author wangbo
* @since 2022/5/5 15:56
*/
public class Demo {
public static void main(String[] args) {
ShapeCache.loadShape();
System.out.println(ShapeCache.getShape(1).getType());//Circle
System.out.println(ShapeCache.getShape(2).getType());//Rectangle
}
}
6、适配器模式
对一个类进行拓展,但不改变原有的类,只是通过新增功能点的类来适配原有类的功能
/**
* 普通媒体播放器
*
* @author wangbo
* @since 2022/5/5 16:23
*/
public interface MediaPlayer {
void play(String type,String description);
}
/**
* 高级播放器
*
* @author wangbo
* @since 2022/5/5 16:27
*/
public interface AdvancedMediaPlayer {
void playVlc(String description);
void playMp4(String description);
}
//需要将普通播放器里融入进来高级播放器,但不改变原有的普通播放器,此时需要一个适配器类来实现普通播放器类新增高级播放器类功能
/**
* MP4播放器
*
* @author wangbo
* @since 2022/5/5 16:33
*/
public class Mp4Player implements AdvancedMediaPlayer{
@Override
public void playVlc(String description) {
}
@Override
public void playMp4(String description) {
System.out.println("Mp4Player..."+description);
}
}
/**
* Vlc播放器
*
* @author wangbo
* @since 2022/5/5 16:32
*/
public class VlcPlayer implements AdvancedMediaPlayer{
@Override
public void playVlc(String description) {
System.out.println("VlcPlayer...."+description);
}
@Override
public void playMp4(String description) {
}
}
/**
* Vlc和Mp4的拓展类
*
* @author wangbo
* @since 2022/5/5 16:35
*/
public class MediaAdapter implements MediaPlayer{
private AdvancedMediaPlayer advancedMediaPlayer;
public MediaAdapter(String type) {
if ("vlc".equals(type)) {
advancedMediaPlayer = new VlcPlayer();
} else if ("mp4".equals(type)) {
advancedMediaPlayer = new Mp4Player();
}
}
@Override
public void play(String type, String description) {
if ("vlc".equals(type)) {
advancedMediaPlayer.playVlc(description);
} else if ("mp4".equals(type)) {
advancedMediaPlayer.playMp4(description);
}
}
}
/**
* 普通播放器+VLC+mp4播放器
*
* @author wangbo
* @since 2022/5/5 16:42
*/
public class AudioPlayer implements MediaPlayer{
private MediaAdapter mediaAdapter;
@Override
public void play(String type, String description) {
if ("mp3".equals(type)) {
System.out.println("mp3....");
} else if ("vlc".equals(type) || "mp4".equals(type)) {
mediaAdapter = new MediaAdapter(type);
mediaAdapter.play(type, description);
}
}
}
/**
* @author wangbo
* @since 2022/5/5 16:47
*/
public class Demo {
public static void main(String[] args) {
AudioPlayer audioPlayer = new AudioPlayer();
audioPlayer.play("mp3", "");
audioPlayer.play("mp4","mp4");
audioPlayer.play("vlc", "vlc");
/**
* mp3....
* Mp4Player...mp4
* VlcPlayer....vlc
*/
}
}
7、桥接模式
将抽象和行为划分开来,各自独立,但能动态的结合
创建对象是创建对象,具体的行为方式是单独的
/**
* 抽象行为接口
*
* @author wangbo
* @since 2022/5/5 17:15
*/
public interface DrawAPI {
void shape();
}
/**
* 具体行为方式
*
* @author wangbo
* @since 2022/5/5 17:18
*/
public class GreenCircle implements DrawAPI{
@Override
public void shape() {
System.out.println("GreenCircle...");
}
}
/**
* 具体行为方式
*
* @author wangbo
* @since 2022/5/5 17:17
*/
public class RedCircle implements DrawAPI{
@Override
public void shape() {
System.out.println("RedCircle...");
}
}
/**
* 对象创建使用行为
*
* @author wangbo
* @since 2022/5/5 17:20
*/
public abstract class Shape {
protected DrawAPI drawAPI;
public Shape(DrawAPI drawAPI) {
this.drawAPI = drawAPI;
}
public abstract void draw();
}
/**
* 直接使用对象 来实现行为
*
* @author wangbo
* @since 2022/5/5 17:21
*/
public class Circle extends Shape{
public Circle(DrawAPI drawAPI) {
super(drawAPI);
}
@Override
public void draw() {
drawAPI.shape();
}
}
Demo
/**
* @author wangbo
* @since 2022/5/5 17:24
*/
public class Demo {
public static void main(String[] args) {
Circle circle = new Circle(new RedCircle());
circle.draw();
Circle circle1 = new Circle(new GreenCircle());
circle1.draw();
/**
* RedCircle...
* GreenCircle...
*/
}
}
8、过滤器模式
可以根据数据组合多个标准以获得单个符合条件的标准
/**
* @author wangbo
* @since 2022/5/5 18:17
*/
public class Person {
private String name;
private String gender;
private String maritalStatus;
public Person(String name, String gender, String maritalStatus){
this.name = name;
this.gender = gender;
this.maritalStatus = maritalStatus;
}
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public String getMaritalStatus() {
return maritalStatus;
}
}
/**
* 根据不同条件对person数据进行过滤
*
* @author wangbo
* @since 2022/5/5 18:19
*/
public interface Criteria {
List<Person> meetCriteria(List<Person> persons);
}
/**
* @author wangbo
* @since 2022/5/5 18:39
*/
public class CriteriaFemale implements Criteria{
@Override
public List<Person> meetCriteria(List<Person> persons) {
List<Person> collect = persons.stream().filter(person -> {
if ("Female".equals(person.getGender())) {
return true;
} else {
return false;
}
}).collect(Collectors.toList());
return collect;
}
}
/**
* @author wangbo
* @since 2022/5/5 18:28
*/
public class CriteriaMale implements Criteria {
@Override
public List<Person> meetCriteria(List<Person> persons) {
List<Person> collect = persons.stream().filter(person -> {
if ("Male".equals(person.getGender())) {
return true;
} else {
return false;
}
}).collect(Collectors.toList());
return collect;
}
}
/**
* @author wangbo
* @since 2022/5/5 18:44
*/
public class OrCriteria implements Criteria{
private Criteria criteria;
private Criteria otherCriteria;
public OrCriteria(Criteria criteria, Criteria otherCriteria) {
this.criteria = criteria;
this.otherCriteria = otherCriteria;
}
@Override
public List<Person> meetCriteria(List<Person> persons) {
List<Person> list = criteria.meetCriteria(persons);
List<Person> otherList = otherCriteria.meetCriteria(persons);
list.stream().forEach(item -> {
if (!otherList.contains(item)) {
otherList.add(item);
}
});
return otherList;
}
}
/**
* @author wangbo
* @since 2022/5/5 18:46
*/
public class Demo {
public static void main(String[] args) {
List<Person> persons = new ArrayList<Person>();
persons.add(new Person("Robert","Male", "Single"));
persons.add(new Person("John", "Male", "Married"));
persons.add(new Person("Laura", "Female", "Married"));
persons.add(new Person("Diana", "Female", "Single"));
persons.add(new Person("Mike", "Male", "Single"));
persons.add(new Person("Bobby", "Male", "Single"));
Criteria criteriaMal = new CriteriaMale();
List<Person> list = criteriaMal.meetCriteria(persons);
list.forEach(item -> {
System.out.print(item.getName()+"-");//Robert-John-Mike-Bobby----
});
System.out.println("---");
Criteria criteriaFeMal = new CriteriaFemale();
criteriaFeMal.meetCriteria(persons).forEach(item -> {
System.out.print(item.getName()+"-");//Laura-Diana----
});
System.out.println("---");
Criteria criteriaOr = new OrCriteria(criteriaMal, criteriaFeMal);
criteriaOr.meetCriteria(persons).forEach(item -> {
System.out.print(item.getName()+"-");//Laura-Diana-Robert-John-Mike-Bobby
});
}
}
9、组合模式
组合模式用于需要以同样的方式的方式处理一组对象作为单个对象
对象内部还含有对象
/**
* @author wangbo
* @since 2022/5/5 20:07
*/
public class Employee {
private String name;
private String dept;
private List<Employee> employeeList;
public Employee(String name,String dept) {
this.dept = dept;
this.name = name;
employeeList = new ArrayList<>();
}
public void add(Employee employee) {
employeeList.add(employee);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Employee> getEmployeeList() {
return employeeList;
}
public void setEmployeeList(List<Employee> employeeList) {
this.employeeList = employeeList;
}
}
/**
* @author wangbo
* @since 2022/5/5 20:06
*/
public class Demo {
public static void main(String[] args) {
Employee employee = new Employee("wb","kf");
Employee employee1 = new Employee("zs", "kf");
Employee employee2 = new Employee("ls", "kf");
employee.add(employee1);
employee1.add(employee2);
System.out.println(employee.getName());
System.out.println(employee.getEmployeeList().get(0).getName());
System.out.println(employee.getEmployeeList().get(0).getEmployeeList().get(0).getName());
/**
* wb
* zs
* ls
*/
}
}
10、装饰模式
向现有对象添加新功能而不改变其结构
/**
* @author wangbo
* @since 2022/5/5 20:32
*/
public interface Shape {
void draw();
}
/**
* @author wangbo
* @since 2022/5/5 20:33
*/
public class Circle implements Shape{
@Override
public void draw() {
System.out.println("Circle...");
}
}
/**
* @author wangbo
* @since 2022/5/5 20:33
*/
public class Rectangle implements Shape{
@Override
public void draw() {
System.out.println("Rectangle...");
}
}
/**
* 装饰器抽象类
*
* @author wangbo
* @since 2022/5/5 20:39
*/
public abstract class ShapeDecorator implements Shape {
}
/**
* 具体的装饰类
*
* @author wangbo
* @since 2022/5/5 20:41
*/
public class RedShapeDecorator extends ShapeDecorator{
private Shape shape;
public RedShapeDecorator(Shape shape) {
this.shape = shape;
}
@Override
public void draw() {
//原先方法不动
shape.draw();
//多加的装饰方法
print();
}
public void print() {
System.out.println("This is RedShapeDecorator...");
}
}
/**
* @author wangbo
* @since 2022/5/5 20:31
*/
public class Demo {
public static void main(String[] args) {
RedShapeDecorator redShapeDecorator = new RedShapeDecorator(new Circle());
redShapeDecorator.draw();
/**
* Circle...
* This is RedShapeDecorator...
*/
RedShapeDecorator shapeDecorator = new RedShapeDecorator(new Rectangle());
shapeDecorator.draw();
/**
* Rectangle...
* This is RedShapeDecorator...
*/
}
}
11、外观模式
隐藏创建对象和行为,对外提供接口访问对象行为的叫做外观,内部处理了复杂行为
/**
* @author wangbo
* @since 2022/5/5 21:03
*/
public interface Shape {
void draw();
}
/**
* @author wangbo
* @since 2022/5/5 21:03
*/
public class Rectangle implements Shape{
@Override
public void draw() {
System.out.println("Rectangle...");
}
}
/**
* @author wangbo
* @since 2022/5/5 21:04
*/
public class Square implements Shape{
@Override
public void draw() {
System.out.println("Square...");
}
}
/**
* 外观类
*
* @author wangbo
* @since 2022/5/5 21:05
*/
public class ShapeMaker {
private Shape rectangle;
private Shape square;
public ShapeMaker() {
this.rectangle = new Rectangle();
this.square = new Square();
}
public void rectangleDraw() {
rectangle.draw();
}
public void squareDraw() {
square.draw();
}
}
/**
* @author wangbo
* @since 2022/5/5 20:59
*/
public class Demo {
public static void main(String[] args) {
ShapeMaker shapeMaker = new ShapeMaker();
shapeMaker.rectangleDraw();
shapeMaker.squareDraw();
/**
* Rectangle...
* Square...
*/
}
}
12、享元模式
享元模式主要用于减少创建的对象数量,并减少内存占用并提高性能,使大家共享一个类(元类).
/**
* @author wangbo
* @since 2022/5/6 10:26
*/
public interface Shape {
void draw();
}
/**
* 元类,以后获取对象行为有对象的话直接复用
*
* @author wangbo
* @since 2022/5/6 10:26
*/
public class Circle implements Shape{
private String color;
private String colorSign;
public Circle(String color) {
this.color = color;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getColorSign() {
return colorSign;
}
public void setColorSign(String colorSign) {
this.colorSign = colorSign;
}
@Override
public void draw() {
System.out.println("Circle..."+colorSign);
}
}
/**
* 封装对象工厂,同一个对象可以复用,用的其实是一个map存的对象属性
*
* @author wangbo
* @since 2022/5/6 10:32
*/
public class ShapeFactory {
private static Map<String,Shape> map = new HashMap<>();
public static Circle getShape(String color) {
Circle shape = (Circle) map.get(color);
if (shape == null) {
shape = new Circle(color);
map.put(color, shape);
System.out.println("放入一个shape对象。。。"+color);
}
return shape;
}
}
/**
* @author wangbo
* @since 2022/5/6 10:24
*/
public class Demo {
public static void main(String[] args) {
Circle red = ShapeFactory.getShape("red");//放入一个shape对象。。。red
red.setColorSign("1");
red.draw();//Circle...1
red.setColorSign("2");
red.draw();//Circle...2
Circle green = ShapeFactory.getShape("green");//放入一个shape对象。。。green
green.setColorSign("3");
green.draw();//Circle...3
Circle green1 = ShapeFactory.getShape("green");
green1.draw();//Circle...3
}
}
13、责任链模式
接口请求,处理不了的交给下个处理,逐一处理
/**
* 递归---自己方法调用自己
* 对象包含自己对象,自己对象处理不了,交给子对象去处理,直到结束
*
* @author wangbo
* @since 2022/5/6 10:56
*/
public abstract class AbstractLogger {
protected AbstractLogger nextLogger;
protected Integer level;
public AbstractLogger getNextLogger() {
return nextLogger;
}
public void setNextLogger(AbstractLogger nextLogger) {
this.nextLogger = nextLogger;
}
public void logMessage(Integer level) {
if (this.level <= level) {
write();
}
if (this.nextLogger != null) {
this.nextLogger.logMessage(level);
}
}
abstract void write();
}
/**
*
* @author wangbo
* @since 2022/5/6 10:59
*/
public class ConsoleLogger extends AbstractLogger{
public ConsoleLogger(Integer level) {
this.level = level;
}
@Override
void write() {
System.out.println("ConsoleLogger...");
}
}
/**
* @author wangbo
* @since 2022/5/6 11:03
*/
public class DebugLogger extends AbstractLogger{
public DebugLogger(Integer level) {
this.level = level;
}
@Override
void write() {
System.out.println("DebugLogger...");
}
}
/**
* @author wangbo
* @since 2022/5/6 11:02
*/
public class ErrorLogger extends AbstractLogger{
public ErrorLogger(Integer level) {
this.level = level;
}
@Override
void write() {
System.out.println("ErrorLogger...");
}
}
/**
* @author wangbo
* @since 2022/5/6 10:54
*/
public class Demo {
public static void main(String[] args) {
AbstractLogger consoleLogger = new ConsoleLogger(1);
AbstractLogger debugLogger = new DebugLogger(2);
AbstractLogger errorLogger = new ErrorLogger(3);
consoleLogger.setNextLogger(debugLogger);
debugLogger.setNextLogger(errorLogger);
consoleLogger.logMessage(3);
/**
* ConsoleLogger...
* DebugLogger...
* ErrorLogger...
*/
consoleLogger.logMessage(1);
/**
* ConsoleLogger..
*/
}
}
14、命令模式
调用方发出命令给目标对象,实际上是目标对象内部已经对行为进行了封装,调用发只是发送请求,具体的执行还在目标对象上。
使用命令模式来标识哪个对象,并根据命令类型执行哪个命令
命令模式:指定具体对象执行具体行为
/**
* 统一命令行为
*
* @author wangbo
* @since 2022/5/6 11:35
*/
public class Stock {
public void buy() {
System.out.println("buy...");
}
public void sell() {
System.out.println("sell...");
}
}
/**
* 统一方法
*
* @author wangbo
* @since 2022/5/6 11:31
*/
public interface Order {
void execute();
}
/**
* 具体对象执行具体行为
*
* @author wangbo
* @since 2022/5/6 11:40
*/
public class BuyStock implements Order{
private Stock stock;
public BuyStock(Stock stock) {
this.stock = stock;
}
@Override
public void execute() {
this.stock.buy();
}
}
/**
* @author wangbo
* @since 2022/5/6 11:41
*/
public class SellStock implements Order{
private Stock stock;
public SellStock(Stock stock) {
this.stock = stock;
}
@Override
public void execute() {
this.stock.sell();
}
}
/**
* 封装行为和对象
*
* @author wangbo
* @since 2022/5/6 11:45
*/
public class Broker {
private List<Order> list = new ArrayList<>();
public void addOrder(Order order) {
list.add(order);
}
public void executeOrder() {
list.stream().forEach(item -> {
item.execute();
});
}
}
/**
* @author wangbo
* @since 2022/5/6 11:30
*/
public class Demo {
public static void main(String[] args) {
Stock stock = new Stock();
Broker broker = new Broker();
broker.addOrder(new BuyStock(stock));
broker.addOrder(new SellStock(stock));
broker.executeOrder();
/**
* buy...
* sell...
*/
}
}
15、中介者模式
对象和对象之间的各自行为通过中介的类行为来展示,处理不同类之间的所有通信(行为)
对对象的行为单独抽取出来(放入中介中)进行执行
/**
* @author wangbo
* @since 2022/5/6 14:36
*/
public class User {
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void sendMessage(String message) {
Room.sendRoomMessage(this, message);
}
}
/**
* 存放对象行为执行的中介者
*
* @author wangbo
* @since 2022/5/6 14:41
*/
public class Room {
public static void sendRoomMessage(User user,String message) {
System.out.println(user.getName()+"----"+message);
}
}
/**
* @author wangbo
* @since 2022/5/6 14:45
*/
public class Demo {
public static void main(String[] args) {
User user = new User("zs");
User user1 = new User("ls");
user.sendMessage("zsmessgae...");
user1.sendMessage("lsmessgae...");
/**
* zs----zsmessgae...
* ls----lsmessgae...
*/
}
}
16、备忘录模式
/**
* 每一次状态变化,保存的对象状态
* 中转类
*
* @author wangbo
* @since 2022/5/6 15:10
*/
public class Memento {
private Integer state;
public Memento(Integer state) {
this.state = state;
}
public Integer getState() {
return state;
}
}
/**
* 对象刚初创建 使用的类;
*
* @author wangbo
* @since 2022/5/6 15:11
*/
public class Originator {
private Integer state;
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
public Memento saveMemento() {
return new Memento(this.state);
}
public void getStateFromMemento(Memento memento) {
this.state = memento.getState();
}
}
/**
* list保存旧状态的类
* 可以随时获取之前状态的类
*
* @author wangbo
* @since 2022/5/6 15:15
*/
public class CareTaker {
public List<Memento> list = new ArrayList<>();
public void addMemento(Memento memento) {
list.add(memento);
}
public Memento getMemento(int index) {
return list.get(index);
}
}
/**
* @author wangbo
* @since 2022/5/6 15:06
*/
public class Demo {
public static void main(String[] args) {
CareTaker careTaker = new CareTaker();
Originator originator = new Originator();
//第一种状态
originator.setState(1);
Memento memento = originator.saveMemento();
careTaker.addMemento(memento);
//第二种状态
originator.setState(2);
Memento memento1 = originator.saveMemento();
careTaker.addMemento(memento1);
//第三种状态
originator.setState(3);
Memento memento2 = originator.saveMemento();
careTaker.addMemento(memento2);
//获取状态保存的集合
System.out.println(careTaker.list);//[com.memento.Memento@2437c6dc, com.memento.Memento@1f89ab83, com.memento.Memento@e73f9ac]
//回退到第一种状态
Memento memento3 = careTaker.getMemento(0);
originator.getStateFromMemento(memento3);
System.out.println(originator.getState());//1
}
}
17、观察者模式
一个对象被修改,它的依赖对象将被自动通知,告诉当前对象修改的情况
/**
* 观察的对象
* 每次setState方法变动,查出来对象的变化
*
* @author wangbo
* @since 2022/5/6 15:54
*/
public class Subject {
private List<Observer> list = new ArrayList<>();
private int state;
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
this.update();
}
public void addObserver(Observer observer) {
list.add(observer);
}
public void update() {
list.stream().forEach(item -> {
item.update();
});
}
}
/**
* @author wangbo
* @since 2022/5/6 15:58
*/
public abstract class Observer {
protected Subject subject;
public abstract void update();
}
/**
* @author wangbo
* @since 2022/5/6 16:13
*/
public class OctalObserver extends Observer{
public OctalObserver(Subject s) {
subject = s;
subject.addObserver(this);
}
@Override
public void update() {
System.out.println(subject.getState()+"---"+"OctalObserver");
}
}
/**
* @author wangbo
* @since 2022/5/6 16:02
*/
public class BinaryObserver extends Observer{
public BinaryObserver(Subject s) {
subject = s;
subject.addObserver(this);
}
@Override
public void update() {
System.out.println(subject.getState()+"----"+"BinaryObserver");
}
}
/**
* @author wangbo
* @since 2022/5/6 15:52
*/
public class Demo {
public static void main(String[] args) {
Subject subject = new Subject();
BinaryObserver binaryObserver = new BinaryObserver(subject);
OctalObserver octalObserver = new OctalObserver(subject);
subject.setState(1);
/**
* 1----BinaryObserver
* 1---OctalObserver
*/
}
}
18、空对象模式
在空对象模式中,一个空对象取代 NULL 对象实例的检查;
避免空对象引起的空指针,而空对象可以指定业务行为执行。
/**
* @author wangbo
* @since 2022/5/7 17:21
*/
public abstract class AbstractCustomer {
protected String name;
public abstract Boolean isNUll();
public abstract void getName();
}
/**
* 真实对象
*
* @author wangbo
* @since 2022/5/7 17:27
*/
public class RealCustomer extends AbstractCustomer{
public RealCustomer(String na) {
name = na;
}
@Override
public Boolean isNUll() {
return false;
}
@Override
public void getName() {
System.out.println("This is RealCustomer..."+this.name);
}
}
/**
* 空对象处理
*
* @author wangbo
* @since 2022/5/7 17:30
*/
public class NullCustomer extends AbstractCustomer{
public NullCustomer(String na) {
name = na;
}
@Override
public Boolean isNUll() {
return true;
}
@Override
public void getName() {
System.out.println("This is NullCustomer..."+this.name);
}
}
/**
* 得到对象是真还是空,进行处理 而不是空指针处理
*
* @author wangbo
* @since 2022/5/7 17:32
*/
public class CustomerFactory {
private static String[] names = {"wb","zs","ls","we"};
public static AbstractCustomer getCustomer(String name) {
for(String na:names) {
if (na.equals(name)) {
return new RealCustomer(name);
}
}
return new NullCustomer(name);
}
}
/**
* @author wangbo
* @since 2022/5/7 17:15
*/
public class Demo {
public static void main(String[] args) {
AbstractCustomer wb = CustomerFactory.getCustomer("wb");
wb.getName();//This is RealCustomer...wb
AbstractCustomer www = CustomerFactory.getCustomer("www");
www.getName();//This is NullCustomer...www
}
}
19、策略模式
创建表示各种策略对象和其行为根据其策略对象而变化的上下文对象。
策略对象更改上下文对象的执行算法。
注意:Context需要事先将对象构建好执行构造方法,对象构建可以根据if-else来提前map构造
/**
* 整体策略接口
*
* @author wangbo
* @since 2022/5/7 17:53
*/
public interface Strategy {
void operation();
}
/**
* @author wangbo
* @since 2022/5/7 17:54
*/
public class StartStrategy implements Strategy{
@Override
public void operation() {
System.out.println("StartStrategy...");
}
}
/**
* @author wangbo
* @since 2022/5/7 17:55
*/
public class StopStrategy implements Strategy{
@Override
public void operation() {
System.out.println("StopStrategy...");
}
}
/**
* 上下文联系执行某种策略
*
* @author wangbo
* @since 2022/5/7 17:56
*/
public class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void finalStrategy() {
strategy.operation();
}
}
/**
* @author wangbo
* @since 2022/5/7 17:50
*/
public class Demo {
public static void main(String[] args) {
Context context = new Context(new StartStrategy());
context.finalStrategy();//StartStrategy...
context = new Context(new StopStrategy());
context.finalStrategy();//StopStrategy...
}
}
20、模板模式
定义一个操作中算法的骨架,将一些步骤的执行延迟到其子类中
/**
* 基础骨架
*/
public abstract class Game {
public abstract void init();
public abstract void start();
public abstract void end();
public final void play() {
init();
start();
System.out.println("This is template...");
end();
}
}
public class Cricket extends Game{
@Override
public void init() {
System.out.println("Cricket ...init");
}
@Override
public void start() {
System.out.println("Cricket ...start");
}
@Override
public void end() {
System.out.println("Cricket ...end");
}
}
public class Football extends Game{
@Override
public void init() {
System.out.println("Football ...init");
}
@Override
public void start() {
System.out.println("Football ...start");
}
@Override
public void end() {
System.out.println("Football ...end");
}
}
public class Demo {
public static void main(String[] args) {
Game cricket = new Cricket();
cricket.play();
/**
* Cricket ...init
* Cricket ...start
* This is template...
* Cricket ...end
*/
Game football = new Football();
football.play();
/**
* Football ...init
* Football ...start
* This is template...
* Football ...end
*/
}
}