软件设计师:23种设计模式
总图
创建型设计模式
1. 抽象工厂方法模式#
代码
package nwnu.sun.patterns.createtype.abstractfactory;
/**
* 抽象工厂设计模式
*/
public class AbstractFfactory {
public static void main(String[] args) {
//实例化手机工厂来创建手机
Factory factory = new Factory_phone();
Product_Apple product_apple = factory.create_product_apple();
product_apple.create_product();
Product_xiaomi product_xiaomi = factory.create_product_xiaomi();
product_xiaomi.create_product();
}
}
/**
* 定义抽象总工厂
*/
abstract class Factory {
//创建苹果产品
abstract Product_Apple create_product_apple();
//创建小米产品
abstract Product_xiaomi create_product_xiaomi();
}
/**
* 手机工厂
*/
class Factory_phone extends Factory {
@Override
Product_Apple create_product_apple() {
return new Product_new_Iphone();//核心代码
}
@Override
Product_xiaomi create_product_xiaomi() {
return new Product_xiaomi_phone();
}
}
/**
* 平板工厂
*/
class Factory_pad extends Factory {
@Override
Product_Apple create_product_apple() {
return new Product_IPad();
}
@Override
Product_xiaomi create_product_xiaomi() {
return new Product_xiaomi_pad();
}
}
/**
* 抽象Apple产品
*/
abstract class Product_Apple {
abstract void create_product();
}
/**
* 定义IPhone
*/
class Product_Iphone extends Product_Apple {
@Override
void create_product() {
System.out.println("库克创建IPhone手机");
}
}
/**
* 扩展IPhone
*/
class Product_new_Iphone extends Product_Apple {
@Override
void create_product() {
System.out.println("库克创建IPhone新一代手机");
}
}
/**
* 定义IPad
*/
class Product_IPad extends Product_Apple {
@Override
void create_product() {
System.out.println("库克创建iPad");
}
}
/**
* 抽象小米产品
*/
abstract class Product_xiaomi {
abstract void create_product();
}
/**
* 定义小米手机
*/
class Product_xiaomi_phone extends Product_xiaomi {
@Override
void create_product() {
System.out.println("雷军创建小米手机");
}
}
/**
* 定义小米平板
*/
class Product_xiaomi_pad extends Product_xiaomi {
@Override
void create_product() {
System.out.println("雷军创建小米平板");
}
}
2. 工厂方法模式(类)#
代码
package nwnu.sun.patterns.createtype.factorymethed;
/**
* 工厂方法模式
*/
public class FactoryMethed {
public static void main(String[] args) {
Factory factoryA = new FactoryA();
Product productA = factoryA.create_factory();
productA.info();
}
}
interface Factory {
Product create_factory();
}
class FactoryA implements Factory {
@Override
public Product create_factory() {
return new ProducyA();
}
}
class FactoryB implements Factory {
@Override
public Product create_factory() {
return new ProducyB();
}
}
interface Product {
void info();
}
class ProducyA implements Product {
@Override
public void info() {
System.out.println("创建产品A");
}
}
class ProducyB implements Product {
@Override
public void info() {
System.out.println("创建产品B");
}
}
3. 生成器模式#
代码
package nwnu.sun.patterns.structtype.build;
import java.util.ArrayList;
import java.util.List;
/**
* 构造器模式
*/
public class build {
public static void main(String[] args) {
Construct construct = new Construct();
Builder builder1 = new BuilderPlan1();
construct.Construct_build(builder1);
builder1.getresult();
Builder builder2 = new BuilderPlan2();
construct.Construct_build(builder2);
builder2.getresult();
}
}
class Construct {
public Builder Construct_build(Builder builder) {
builder.buildpart();
return builder;
}
}
abstract class Builder {
abstract void buildpart();
abstract Product_apple getresult();
}
class BuilderPlan1 extends Builder {
Product_apple product_apple = new Product_apple();
@Override
void buildpart() {
product_apple.add("手机");
product_apple.add("卡针");
product_apple.add("充电线");
}
@Override
Product_apple getresult() {
product_apple.show();
return product_apple;
}
}
class BuilderPlan2 extends Builder {
Product_apple product_apple = new Product_apple();
@Override
void buildpart() {
product_apple.add("手机");
product_apple.add("卡针");
product_apple.add("充电线");
product_apple.add("18w快充头(牛逼)");
}
@Override
Product_apple getresult() {
product_apple.show();
return product_apple;
}
}
class Product_apple {
List<String> apple = new ArrayList<>();
public void add(String string) {
apple.add(string);
}
public void show() {
System.out.print("产品组成:");
for (String s : apple)
System.out.print(s + " ");
System.out.println("\n");
}
}
4. 原型模式#
代码
package nwnu.sun.patterns.createtype.prototype;
/**
* @author nwnu
* @date 2022/10/15 20:45
* @description 1.0
*/
public class Prototype {
public static void main(String[] args) {
Product product = new Product("iPhone", 1999.0);
System.out.println(product.getName());
System.out.println(product.clone().getName());
}
}
interface Prototy {
public Product clone();
}
class Product implements Prototy {
private String name;
private Double price;
public Product(String name, Double price) {
this.name = name;
this.price = price;
}
public Product() {
}
public String getName() {
return name;
}
@Override
public Product clone() {
Product product = new Product();
product.name = this.name;
product.price = this.price;
return product;
}
}
5. 单例模式#
饿汉式#
/**
* 饿汉式实现单例模式
*/
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
getInstance()方法中添加了synchronized关键字,使其变成一个同步方法,目的是为了在多线程环境下保证单例对象唯一。
优点: 只有在使用时才会实例化单例,一定程度上节约了资源。
缺点: 第一次加载时要立即实例化,反应稍慢。每次调用getInstance()方法都会进行同步,这样会消耗不必要的资源。这种模式一般不建议使用。
懒汉式#
/**
*懒汉式实现单例
*/
class Person {
private static Person person;
private Person() {
}
// synchronized方法,多线程情况下保证单例对象唯一
public static synchronized Person getInstance() {
if(person == null){
person = new Person();
}
return person;
}
}
结构型设计模式
1. 适配器模式(对象+类)#
代码
public class AdapterPattern {
public static void main(String[] args) {
USB usb = new Adapter();
usb.Request();
}
}
class USB {
public void Request() {
System.out.println("USB数据线");
}
}
class Adapter extends USB {
private TypeC typeC = new TypeC();
@Override
public void Request() {
typeC.SpecificRequest();
}
}
class TypeC {
public void SpecificRequest() {
System.out.println("Type-C数据线");
}
}
2. 桥接模式#
代码
package nwnu.sun.patterns.bridge;
/**
* @author nwnu
* @date 2022/10/14 9:18
* @description 1.0
*/
public class Bridge {
public static void main(String[] args) {
//实例车
Car car = new xin_nengyuan();
//设置车颜色
Color red = new Red();
car.setColor(red);
car.setProductname("比亚迪");
car.print_color();
//更改颜色
Color yellow = new Yellow();
car.setColor(yellow);
car.print_color();
}
}
abstract class Car {
protected Color color;
private String productname;
public void setColor(Color color) {
this.color = color;
}
public void setProductname(String productname) {
this.productname = productname;
}
public String getProductname() {
return productname;
}
abstract void print_color();
}
class xin_nengyuan extends Car {
@Override
public void print_color() {
color.print_color(getProductname());
}
}
interface Color {
public void print_color(String product);
}
class Red implements Color {
@Override
public void print_color(String product) {
System.out.println(product + "颜色是: 红色");
}
}
class Yellow implements Color {
@Override
public void print_color(String product) {
System.out.println(product + "颜色是: 黄色");
}
}
重点:将抽象部分与实现部分相分离,使可以独立变化
3. 组合模式#
代码
abstract class AbstractFile {
public String name;
public void printName(int number) {
}
abstract Boolean add(AbstractFile abstractFile);
abstract Boolean remove(AbstractFile abstractFile);
abstract void show(int number);
}
class File extends AbstractFile {
@Override
public Boolean add(AbstractFile abstractFile) {
return false;
}
@Override
public Boolean remove(AbstractFile abstractFile) {
return false;
}
@Override
public void show(int number) {
}
@Override
public void printName(int number) {
System.out.print("文件:");
while (number >= 0) {
System.out.print(" ");
number--;
}
System.out.println(name);
}
public File(String name) {
this.name = name;
}
}
class Folder extends AbstractFile {
private List<AbstractFile> list = new ArrayList<>();
@Override
public Boolean add(AbstractFile abstractFile) {
return list.add(abstractFile);
}
@Override
public Boolean remove(AbstractFile abstractFile) {
return list.remove(abstractFile);
}
@Override
public void printName(int number) {
System.out.print("目录:");
while (number >= 0) {
System.out.print(" ");
number--;
}
System.out.println(name);
}
@Override
public void show(int number) {
for (AbstractFile list : list) {
if (list instanceof File) {
list.printName(number);
} else {
int number1 = number;
list.printName(number);
list.show(number1 + 2);
}
}
}
public Folder(String name) {
this.name = name;
}
}
4. 装饰器模式#
public class Decorat {
public static void main(String[] args) {
Person student = new Student("张三");
student = new DecoratorA(student);
student = new DecoratorB(student);
student.operaction();
//对象链
new DecoratorB(new DecoratorA(new Student("李四"))).operaction();
}
}
class Student extends Person {
public Student(String name) {
this.name = name;
}
@Override
public void operaction() {
System.out.print(name + ":" + "学习");
}
}
/**
* 装饰器
*/
abstract class Decorator extends Person {
protected Person person;//定义指向person的指针
}
/**
* 装饰器A
*/
class DecoratorA extends Decorator {
public DecoratorA(Person person) {
this.person = person;
}
@Override
public void operaction() {
person.operaction();
System.out.print(" 写作业");
}
}
/**
* 装饰器B
*/
class DecoratorB extends Decorator {
public DecoratorB(Person person) {
this.person = person;
}
@Override
public void operaction() {
person.operaction();
System.out.println(" 考试");
}
}
5. 外观模式#
public class Appearance {
public static void main(String[] args) {
Facade facade = new Facade();
facade.function1();
}
}
class Facade {
private System1 system1;
private System2 system2;
private System3 system3;
public Facade() {
system1 = new System1();
system2 = new System2();
system3 = new System3();
}
public void function1() {
system1.run();
}
public void function2() {
system2.run();
}
public void function3() {
system3.run();
}
}
class System1 {
public void run() {
System.out.println("子系统1运行");
}
}
class System2 {
public void run() {
System.out.println("子系统2运行");
}
}
class System3 {
public void run() {
System.out.println("子系统3运行");
}
}
6. 享元模式#
定义:享元模式(Flyweight):运用共享技术有效地支持大量细粒度的对象.[DP]
它通过共享已经存在的对象来大幅度减少需要创建的对象数量、避免大量相似对象的开销,从而提高系统资源的利用率。
结构:
享元(Flyweight )模式中存在以下两种状态:
- 内部状态,即不会随着环境的改变而改变的可共享部分。
- 外部状态,指随环境改变而改变的不可以共享的部分。
享元模式的实现要领就是区分应用中的这两种状态,并将外部状态外部化。
代码:
package nwnu.sun.patterns.structtype.flyweight;
import java.util.*;
/**
* @author nwnu
* @date 2022/10/15 10:15
* @description 1.0
*/
public class Flyweight {
public static void main(String[] args) {
ShapeFactory sha = new ShapeFactory();
Random random = new Random();
String[] color = {"red", "bule", "yellow"};
for (int i = 0; i < 10; i++) {
System.out.println("第" + i + "次创建");
int index = random.nextInt(color.length);
Shape shape = sha.getShape(color[index]);
shape.draw(random.nextInt(100), random.nextInt(200));
}
}
}
class ShapeFactory {
private Map<String, Shape> map = new HashMap<String, Shape>();
public Shape getShape(String key) {
if (!map.containsKey(key)) {
System.out.println("create new circle ,color is:" + key);
map.put(key, new Circle(key));
}
return map.get(key);
}
}
abstract class Shape {
protected String color;
public abstract void draw(int x, int y);
}
class Circle extends Shape {
public Circle(String color) {
this.color = color;
}
@Override
public void draw(int x, int y) {
System.out.println("circle color " + color + "location is:" + x + "," + y);
}
}
7. 代理模式#
代码
package nwnu.sun.patterns.structtype.proxy;
/**
* @author nwnu
* @date 2022/10/15 11:24
* @description 1.0
*/
public class Proxy {
public static void main(String[] args) {
Subject subject = new Realsubject();
subject.buy();
//代理后
System.out.println("-----");
ProxySubject proxySubject = new ProxySubject(subject);
proxySubject.buy();
}
}
/**
* 对象接口
*/
interface Subject {
abstract void buy();
}
/**
* 代理对象
*/
class ProxySubject implements Subject {
protected Subject subject;
public ProxySubject(Subject subject) {
this.subject = subject;
}
@Override
public void buy() {
System.out.println("选房");
subject.buy();
System.out.println("入住");
}
}
/**
* 对象
*/
class Realsubject implements Subject {
@Override
public void buy() {
System.out.println("付钱");
}
}
行为设计模式
1.责任链模式#
代码
package nwnu.sun.patterns.behaivor;
/**
* @author nwnu
* 学生-->请假
* 辅导员(7天)-->院长(15天)-->校长(<30天)
*/
public class Behaivor {
public static void main(String[] args) {
Handler fudaoyuan = new FuDaoYuan().setHandler(new YuanZhang().setHandler(new XiaoZhang()));
fudaoyuan.request(18);
}
}
abstract class Handler {
//后继指针
protected Handler handler;
public Handler setHandler(Handler handler) {
this.handler = handler;
return handler;
}
abstract void request(int days);
}
/**
* 辅导员
*/
class FuDaoYuan extends Handler {
@Override
public void request(int days) {
if (days < 7) {
System.out.println("辅导员审批通过");
} else {
handler.request(days);
}
}
}
/**
* 院长
*/
class YuanZhang extends Handler {
@Override
public void request(int days) {
if (days < 15) {
System.out.println("院长审批通过");
} else {
handler.request(days);
}
}
}
/**
* 校长
*/
class XiaoZhang extends Handler {
@Override
public void request(int days) {
System.out.println("校长审批通过");
}
}
2.命令模式#
代码
package nwnu.sun.patterns.behaivor;
/**
* @author nwnu
* @date 2022/10/15 17:21
* @description 1.0
*/
public class Commandmoshi {
public static void main(String[] args) {
Tv tv = new Tv();
Command command_on = new OnCommand(tv);//开机
Command command_off = new OffCommand(tv);//关机
Invoker invoker = new Invoker();//执行命令
System.out.println("=======开机=======");
invoker.setCommand(command_on);
invoker.call();
System.out.println("========关机=======");
invoker.setCommand(command_off);
invoker.call();
}
}
class Invoker {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void call() {
command.execute();
}
}
class Tv { // 接受者
public void OnAction() {
System.out.println("成功执行开机");
}
public void OffAction() {
System.out.println("成功执行关机");
}
}
abstract class Command { // 命令接口
protected Tv tv;
abstract void execute();
}
class OnCommand extends Command {//开机命令
public OnCommand(Tv tv) {
this.tv = tv; //调用tv的OnAction()方法
}
@Override
public void execute() {
tv.OnAction();
}
}
class OffCommand extends Command {//关机命令
public OffCommand(Tv tv) {
this.tv = tv;//调用tv的OffAction()方法
}
@Override
public void execute() {
tv.OffAction();
}
}
3.解释器模式(类)#
代码
package nwnu.sun.patterns.behaivor;
import java.util.*;
/**
* @author nwnu
* 解释器设计模式
* 文法例子:
* 区域: A区,B区,C区
* 人员: 开发人员,测试人员,运维人员
* 识别: A区的开发人员
*/
public class Expression {
public static void main(String[] args) {
Context context = new Context();
context.check("A区的开发人员");
context.check("*区的开发人员");
}
}
class Context {
private String[] region = {"A区", "B区", "C区"};
private String[] person = {"开发人员", "测试人员", "运维人员"};
private NonTermainalExpression nonTermainalExpression;
public Context() {
nonTermainalExpression = new NonTermainalExpression(new TerminPression(region), new TerminPression(person));
}
public void check(String str) {
Boolean flag = nonTermainalExpression.Interpret(str);
if (flag) {
System.out.println("识别成功");
} else {
System.out.println("识别失败");
}
}
}
interface AbstractExpression {
public Boolean Interpret(String info);
}
class NonTermainalExpression implements AbstractExpression {// 定义非终结符
private TerminPression region;
private TerminPression person;
public NonTermainalExpression(TerminPression region, TerminPression person) {
this.region = region;
this.person = person;
}
@Override
public Boolean Interpret(String info) {
String[] data = info.split("的");
return region.Interpret(data[0]) && person.Interpret(data[1]);
}
}
class TerminPression implements AbstractExpression {// 定义终结符
private Set<String> set = new HashSet<String>(); //定义规则
public TerminPression(String[] datas) {// 构造器
for (String str : datas) {
set.add(str);
}
}
@Override
public Boolean Interpret(String info) {
return set.contains(info);
}
}
4.迭代器模式#
代码
package nwnu.sun.patterns.createtype.iterator;
import java.util.*;
/**
* @author nwnu
* @date 2022/10/15 21:39
* @description 1.0
*/
public class Iterator {
public static void main(String[] args) {
String[] name = {"数据结构", "计算机组成原理", "计算机网络"};
Double[] price = {78.0, 66.3, 11.6, 15.8};
//数据初始化
BookAggreagte bookAggreagte = new BookAggreagte();
for (int i = 0; i < 3; i++) {
bookAggreagte.add(new Book(name[i], price[i]));
}
//自定义迭代
BookIterator iterator = bookAggreagte.createIterator();
while (iterator.hashNext()) {
Book next = (Book) iterator.Next();
System.out.println(next.getName() + " " + next.getPrice());
}
}
}
interface IteratorSun {
public Boolean hashNext();
public Object Next();
}
class BookIterator implements IteratorSun {
private BookAggreagte bookAggreagte;
private int index;
public BookIterator(BookAggreagte bookAggreagte) {
this.bookAggreagte = bookAggreagte;
}
@Override
public Boolean hashNext() {
if (index < bookAggreagte.size()) {
return true;
}
return false;
}
@Override
public Object Next() {
Book book = bookAggreagte.get(index);
index++;
return book;
}
}
interface Aggreagte {
public BookIterator createIterator();
}
class BookAggreagte implements Aggreagte {
private List<Book> list = new ArrayList<>();
public void add(Book book) {
list.add(book);
}
public int size() {
return list.size();
}
public Book get(int index) {
return list.get(index);
}
/**
* 创建迭代器对象
* @return
*/
@Override
public BookIterator createIterator() {
return new BookIterator(this);
}
}
class Book {
private String name;
private Double price;
public String getName() {
return name;
}
public Double getPrice() {
return price;
}
public Book(String name, Double price) {
this.name = name;
this.price = price;
}
}
5.中介者模式#
代码
package nwnu.sun.patterns.behaivor;
import java.util.*;
/**
* @author nwnu
* 定义中介者:用来绑定各个同事,并在同事之间传递消息
* 同事:通信的对象
* 机制:同事之间不用引用,通过中介者调用,类似于消息队列的作用
*/
public class MediatorPattern {
public static void main(String[] args) {
ColleageA zhangsan = new ColleageA("张三");
ColleageB lisi = new ColleageB("李四");
ConcreateMediator mediator = new ConcreateMediator();
//同事绑定中介者
zhangsan.setMediator(mediator);
lisi.setMediator(mediator);
//中介者维护同事
mediator.addColleage(zhangsan);
mediator.addColleage(lisi);
//张三发送消息
mediator.sendMessage("你好啊", zhangsan);
}
}
interface Mediator {
public void sendMessage(String info, Colleage colleage);//中介者发送消息
}
class ConcreateMediator implements Mediator {
//维护同事
private List<Colleage> list = new ArrayList<>();
public void addColleage(Colleage colleage) {
list.add(colleage);
}
@Override
public void sendMessage(String info, Colleage colleage) {
if (colleage == list.get(0)) {
list.get(1).reciverMessage(info);
} else {
list.get(0).reciverMessage(info);
}
}
}
abstract class Colleage {
protected String name;
protected Mediator mediator;//同事与中介者绑定
abstract void sendMessage(String info, Colleage colleage);
abstract void reciverMessage(String info);
}
/**
* 同事A
*/
class ColleageA extends Colleage {
public ColleageA(String name) {
this.name = name;
}
public void setMediator(Mediator mediator) {
this.mediator = mediator;
}
@Override
public void sendMessage(String info, Colleage colleage) {
mediator.sendMessage(info, this);
}
@Override
public void reciverMessage(String info) {
System.out.println(name + "收到消息:" + info);
}
}
/**
* 同事B
*/
class ColleageB extends Colleage {
public ColleageB(String name) {
this.name = name;
}
public void setMediator(Mediator mediator) {//设置中介者
this.mediator = mediator;
}
@Override
public void sendMessage(String info, Colleage colleage) {
mediator.sendMessage(info, this);
}
@Override
public void reciverMessage(String info) {
System.out.println("同事" + name + "收到消息:" + info);
}
}
6.备忘录模式#
代码
package nwnu.sun.patterns.behaivor;
import com.sun.org.apache.xpath.internal.operations.Or;
import java.util.*;
/**
* @author nwnu
* @date 2022/10/16 12:16
* @description 1.0
*/
public class memoPattern {
public static void main(String[] args) {
Originator originator = new Originator("1024");//备份对象
Caretaker caretaker = new Caretaker();//创建管理者
Memento memento1 = originator.createMemento();//第一次备份
caretaker.add(memento1);
//改变state,再次备份
originator.setstate("2048");
Memento memento2 = originator.createMemento();//第二次备份
caretaker.add(memento2);
//输出所有备份
caretaker.show();
//获取第i次备份
Memento memento = caretaker.get(2);
System.out.println(memento.getState());
}
}
class Originator {
private String state;
public void setstate(String state) {
this.state = state;
}
public String getState() {
return state;
}
public Originator(String state) {
this.state = state;
}
public Memento createMemento() {//创建备份
return new Memento(state);
}
}
class Memento {//备忘录
private String state;
public void setState(String state) {
this.state = state;
}
public String getState() {
return state;
}
public Memento(String state) {
this.state = state;
}
}
class Caretaker {
private List<Memento> mementoList = new ArrayList<Memento>();
public void add(Memento memento) {
mementoList.add(memento);
}
public Memento get(int index) {
if (index > 0 && index <= mementoList.size()) {
return mementoList.get(index - 1);
}
return null;
}
public void show() {
int index = 1;
for (Memento memento : mementoList) {
System.out.println("第" + index + "次备份" + memento.getState());
index++;
}
}
}
7.观察者模式#
代码
package nwnu.sun.patterns.behaivor;
import java.util.*;
import java.util.ArrayList;
/**
* @author nwnu
* @date 2022/10/16 12:50
* @description 1.0
*/
public class ObserverPattern {
public static void main(String[] args) {
BilibiliUp up = new BilibiliUp("杨幂");//定义UP主
ConcreateObserver fans1 = new ConcreateObserver("张三", up);//张三关注up
ConcreateObserver fans2 = new ConcreateObserver("李四", up);//李四关注up
System.out.println("=====更新前=====");
System.out.println("up状态:" + up.getState());
System.out.println(fans1.getName() + "状态:" + fans1.getState());
System.out.println(fans2.getName() + "状态:" + fans1.getState());
up.setState("上线");//Up主更新状态
System.out.println("=====更新后=====");
System.out.println("up状态:" + up.getState());
System.out.println(fans1.getName() + "状态:" + fans1.getState());
System.out.println(fans2.getName() + "状态:" + fans1.getState());
}
}
abstract class Subject {
abstract String getState();
abstract void attach(Observer observer);//注册观察者
abstract void detach(Observer observer);//删除观察者
abstract void notify_Observer();//状态改变后,更新所有观察者
}
class BilibiliUp extends Subject {
private String state = "未上线";
private String name;
private List<Observer> observerlist;
public String getState() {
return state;
}
public String getName() {
return name;
}
public BilibiliUp(String name) {
this.observerlist = new ArrayList<>();
this.name = name;
}
public void setState(String state) {
this.state = state;
notify_Observer();//up更新状态,立即通知粉丝
}
@Override
void attach(Observer observer) {
observerlist.add(observer);
}
@Override
void detach(Observer observer) {
observerlist.remove(observer);
}
@Override
void notify_Observer() {
for (Observer observer : observerlist) {
observer.Update(state);//更新粉丝状态
}
}
}
abstract class Observer {
abstract void Update(String state);
}
class ConcreateObserver extends Observer {
private String state;
private String name;
private Subject subject;
public String getState() {
return state;
}
public String getName() {
return name;
}
public ConcreateObserver(String name, Subject subject) {
this.name = name;
this.state = subject.getState();
subject.attach(this);//初始化up
}
@Override
public void Update(String state) {
this.state = state;
}
}
8.State(状态模式)#
代码
package nwnu.sun.patterns.behaivor.state;
/**
* @author nwnu
* @date 2022/10/16 17:05
* @description 1.0
*/
public class StatePattern {
public static void main(String[] args) {
Context context = new Context();
for (int i = 1; i <= 15; i++) {
context.request();
}
}
}
class Context {//贩卖机
private int conunt;//数量
private State state;//状态
public int getConunt() {
return conunt;
}
public void setConunt(int conunt) {
this.conunt = conunt;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
public Context() {
this.conunt = 5;
this.state = new StateHvProduct();
}
public void request() {
state.handler(this);//依据货物数量更新内部状态
}
}
interface State {
void handler(Context context);
}
class StateHvProduct implements State {//有货
@Override
public void handler(Context context) {
if (context.getConunt() > 0) {
System.out.println("有货,数量:" + context.getConunt());
context.setConunt(context.getConunt() - 1);
} else {
System.out.print("没货! ");
context.setState(new StateNoProduct());//没货,更改内部状态
context.request();//继续请求
}
}
}
class StateNoProduct implements State {//无货
@Override
public void handler(Context context) {
context.setConunt(5);
System.out.println("补货成功,数量5");
context.setState(new StateHvProduct());//补货后,更改内部状态
context.request();//继续请求
}
}
9.策略模式#
代码
package nwnu.sun.patterns.behaivor;
/**
* @author nwnu
* @date 2022/10/16 21:58
* @description 1.0
*/
public class Strategypattern {
public static void main(String[] args) {
Strategy strategy = new PlusStrategy();//定义加策略
TwonumberContext context = new TwonumberContext(strategy);
context.operation(5, 1);
}
}
/**
* 客户,调用具体算法
*/
class TwonumberContext {
private Strategy strategy;
public TwonumberContext(Strategy strategy) {
this.strategy = strategy;
}
public void operation(int a, int b) {
strategy.twonumber_opreation(a, b);
}
}
/**
* 算法 接口
*/
interface Strategy {
public void twonumber_opreation(int a, int b);
}
/**
* 加法策略
*/
class PlusStrategy implements Strategy {
@Override
public void twonumber_opreation(int a, int b) {
System.out.println(a + "+" + b + "=" + (a + b));
}
}
/**
* 加法策略
*/
class JianStrategy implements Strategy {
@Override
public void twonumber_opreation(int a, int b) {
System.out.println(a + "-" + b + "=" + (a - b));
}
}
10.模板方法(类)#
代码
package nwnu.sun.patterns.behaivor;
/**
* @author nwnu
* @date 2022/10/16 23:06
* @description 1.0
*/
public class TemplateMethedPattern {
public static void main(String[] args) {
Person student = new Student();
Person teacher = new Teacher();
student.TemplateMethed();
teacher.TemplateMethed();
}
}
abstract class Person {
public void TemplateMethed() {
System.out.println("进教室");
PrimitiveOperation1();
System.out.println("出教室");
PrimitiveOperation2();
}
public abstract void PrimitiveOperation1();
public abstract void PrimitiveOperation2();
}
class Student extends Person {
@Override
public void PrimitiveOperation1() {
System.out.println("学生听课");
}
@Override
public void PrimitiveOperation2() {
System.out.println("学生写作业");
}
}
class Teacher extends Person {
@Override
public void PrimitiveOperation1() {
System.out.println("老师讲课");
}
@Override
public void PrimitiveOperation2() {
System.out.println("老师布置作业");
}
}
访问者模式#
代码
package nwnu.sun.patterns.behaivor;
import java.util.ArrayList;
import java.util.List;
/**
* @author nwnu
* @date 2022/10/17 0:16
* @description 1.0
*/
public class Visitorpattern {
public static void main(String[] args) {
Struct struct = new Struct();
Visitor visitor1 = new Visitor1();
Visitor visitor2 = new Visitor2();
struct.visit(visitor1);
System.out.println("=====");
struct.visit(visitor2);
}
}
interface Visitor {
void visitStudent(StudentV studentV);
void visitTeacher(PersonV personV);
}
class Visitor1 implements Visitor { // 访问者1
@Override
public void visitStudent(StudentV studentV) {
System.out.println("访问者1访问学生:" + studentV.name);
}
@Override
public void visitTeacher(PersonV personV) {
System.out.println("访问者1访问老师:" + personV.name);
}
}
class Visitor2 implements Visitor { // 访问者2
@Override
public void visitStudent(StudentV studentV) {
System.out.println("访问者2访问:" + studentV.name);
}
@Override
public void visitTeacher(PersonV personV) {
System.out.println("访问者2访问:" + personV.name);
}
}
class Struct {
private List<PersonV> personVList = new ArrayList<>();
public Struct() {
personVList.add(new StudentV("张三"));
personVList.add(new StudentV("李四"));
personVList.add(new StudentV("王五"));
personVList.add(new TeacherV("李老师"));
personVList.add(new TeacherV("陈老师"));
personVList.add(new TeacherV("王老师"));
}
public void visit(Visitor visitor) {
for (PersonV personV : personVList) {
personV.accept(visitor);
}
}
}
abstract class PersonV {
protected String name;
abstract void accept(Visitor visitor);
}
class StudentV extends PersonV {
public StudentV(String name) {
this.name = name;
}
public void accept(Visitor visitor) {
visitor.visitStudent(this);
}
}
class TeacherV extends PersonV {
public TeacherV(String name) {
this.name = name;
}
public void accept(Visitor visitor) {
visitor.visitTeacher(this);
}
}
作者:Esofar
出处:https://www.cnblogs.com/nwnusun/p/16797741.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
标签: java Buy me a cup of coffee ☕. 好文要顶 关注我 收藏该文 匿名者nwnu
粉丝 - 0 关注 - 6
+加关注 0 0 « 上一篇: RPM方式安装oracle
» 下一篇: Yarn原理解析 posted @ 2022-10-17 01:03 匿名者nwnu 阅读(66) 评论(0) 编辑 收藏 举报 刷新评论刷新页面返回顶部 发表评论 编辑 预览 88ee990f-bb7c-489a-46fb-08d6d3fea897 自动补全
[Ctrl+Enter快捷键提交]
【腾讯云】新春采购节:抢爆款云服务器每月9元起,个人开发者加享折上折 <iframe data-google-container-id="1" data-load-complete="true" frameborder="0" height="250" id="google_ads_iframe_/1090369/C1_0" marginheight="0" marginwidth="0" name="google_ads_iframe_/1090369/C1_0" scrolling="no" style="border: 0; vertical-align: bottom" title="3rd party ad content" width="300"></iframe> 编辑推荐:· RabbitMQ 真实生产故障问题还原与分析
· .netcore 全局异常处理
· [C#异步]异步多线程的本质,上下文流转和同步
· .NET AsyncLocal 避坑指南
· 我的十年编程路 2013年篇
阅读排行:
· 【故障公告】攻击式巨量并发请求再次来袭,引发博客站点故障
· 自己做一个ChatGPT微信小程序(代码开源)
· 用MiniPC搭建个人服务器
· 【Redis场景5】集群秒杀优化-分布式锁
· RabbitMQ真实生产故障问题还原与分析
标签:String,void,class,new,设计模式,public,out From: https://www.cnblogs.com/fanwenyan/p/17182616.html