(Zst_2001)B站-面向对象软考笔记简

面向对象

面向对象基础

image-20231016231701149


对象和消息

image-20231016233309899


方法重载

image-20231016235830710


封装

image-20231017084501095


控制修饰符的限定范围

image-20231017084904812


继承

image-20231017085714299


子类父类**
类的加载顺序

子类在继承父类时,子类只继承父类的非私有方法或属性;

image-20231017085556673


示例

image-20231017090101567


image-20231017090353645


多态

image-20231017091151422


image-20231017091415765


动态绑定

image-20231017092233030


面向对象设计原则

image-20231017093002988


image-20231017093102344


面向对象分析(OOA)

image-20231017103937711


image-20231017104025840


面向对象设计(OOD)

image-20231017104436116


面向对象测试

image-20231017104633541


面向对象程序设计(OOP)

image-20231017105908803


UML

image-20231017111757118


事务

对模型中具有代表性的成分的抽象;

image-20231017112359010


image-20231017112525897


关系

依赖

image-20231017112913745

关联

image-20231017114103834


泛化

image-20231017114242858


实现

image-20231017114357648


关联多重度

image-20231018091935301


image-20231018092623955


UML中的图

image-20231018094250059


类图

image-20231018094459300


示例

重写(覆盖)

image-20231018094726674


对象图

image-20231018100257366


用例图

image-20231018100840516


包含关系

image-20231018103530362


扩展关系

image-20231018104410480


泛化关系

image-20231018104907853


用例图的概念

image-20231018105359226


image-20231018105440638


交互图(序列图-顺序图)

image-20231018110820747


image-20231018110903860


image-20231018110935979


image-20231018111037430


通信图

image-20231018113521096


状态图

image-20231018231155433


状态和活动

image-20231018232343223


image-20231018232419485


转换和事件

image-20231018233921118


image-20231018233953017


状态图的概念

image-20231018234722130


示例

image-20231018235312132


活动图

image-20231019090446618


image-20231019090546889


构件图

image-20231019091749658


部署图

image-20231019092616029


设计模式

设计模式的要素

image-20231019094943442


设计模式分类汇总

image-20231019094832087


创建型设计模式

image-20231019100558175


简单工厂模式

image-20231019104422526


工厂方法模式

image-20231019105917278


工厂方法模式相关概念

image-20231019110335252


抽象工厂模式

image-20231019111256341


抽象工厂模式的适用性

image-20231019114239583


生成器模式

image-20231019113558423


生成器模式的适用性

image-20231019113651891


原型模式

image-20231021110404564


原型模式的适用性

image-20231021110525503


原型设计模式(入门code)
public class ImitationPrototype {
    public static void main(String[] args) {
        product product = new product(123, 123456.0);
        System.out.println("product = "+product.getId()+" / "+product.getPrice());
        product clone1 = (product) product.Clone();
        System.out.println("clone1 = "+clone1.getId()+" / "+clone1.getPrice());

    }
}

interface Prototype {
    public Object Clone();
}
class product implements Prototype{
    private int id ;

    public product(int id, double price) {
        this.id = id;
        this.price = price;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    private double price ;

    public product() {
    }

    @Override
    public Object Clone() {
        product product = new product();
        product.id = this.id;
        product.price = this .price ;
        return product ;
    }
}

单例设计模式

image-20231021112930642


单例设计模式code
public class imitationSingleton {
    public static void main(String[] args) {
//        Singleton singleton = new Singleton();
        Singleton singleton = Singleton.getSingleton();
        System.out.println(singleton);
        singleton.setNum(80);
        System.out.println(" /  "+singleton.getNum());
    }
}

class Singleton {
    private int num ;

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public static Singleton getInstance() {
        return instance;
    }

    public static void setInstance(Singleton instance) {
        Singleton.instance = instance;
    }

    private static Singleton instance =  new Singleton() ;
    private Singleton(){};
    public static Singleton getSingleton(){
        return instance ;
    }
}


结构型设计模式

适配器模式(Adapter)

image-20231021114856947


适配器设计模式的适用性

image-20231021115113912


适配器设计模式code
package com.tom.结构型设计模式;

public class imitationAdapter {
    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("TypeC-数据线");
    }
}
桥接模式(Bridge)

image-20231021122347671


桥接设计模式的适用性

image-20231021122430659


桥接设计模式code
package com.tom.结构型设计模式;

import java.awt.*;

public class ImitationBridge {
    public static void main(String[] args) {
        ProductA productA = new ProductA();
        Color red = new Red();
        Color blue = new Blue();
        productA.setName("产品A");
        productA.setColor(red);
        productA.Operation();
    }
}
abstract class Product{
    private String name ;
    protected Color color ;

    public Product() {
    }

    public Product(String name, Color color) {
        this.name = name;
        this.color = color;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Color getColor() {
        return color;
    }

    public void setColor(Color color) {
        this.color = color;
    }

    public abstract void Operation () ;
}
class ProductA extends  Product{
    @Override
    public void Operation() {
        color.OperationImp(this.getName());
    }
}

interface Color {

    public void OperationImp(String name);

}
class Red implements Color {

    @Override
    public void OperationImp(String name) {
        System.out.println(name+": 红色");
    }
}
class Blue implements Color{

    @Override
    public void OperationImp(String name) {
        System.out.println(name+ ": 蓝色 ");
    }
    
}

组合模式(Composite)

image-20231021130113987


组合设计模式式添加删除code
package com.tom.结构型设计模式;

import java.util.ArrayList;
import java.util.List;

public class ImitationComposite {
    public static void main(String[] args) {
        AbstractFile root = new Folder("root");
        AbstractFile folder = new Folder("FolderA");
        AbstractFile file = new File("FileA");
        System.out.println(root.Add(folder));
        System.out.println(root.Add(file));

    }
}
abstract class AbstractFile{
   protected String name ;
   public void printName(){
       System.out.println(name);
   }
   public abstract boolean Add(AbstractFile file);
   public abstract boolean Delete(AbstractFile file);
}
class Folder extends AbstractFile{
    private List<AbstractFile> childLlsit = new ArrayList<AbstractFile> () ;
    public Folder(String name){
        this.name = name ;
    }

    @Override
    public boolean Add(AbstractFile file) {
        childLlsit.add(file);
        return true ;
    }

    @Override
    public boolean Delete(AbstractFile file) {
        childLlsit.remove(file);
        return true;
    }
}
class File extends AbstractFile{
    public File (String name){
        this.name = name ;
    }

    @Override
    public boolean Add(AbstractFile file) {
        return false;
    }

    @Override
    public boolean Delete(AbstractFile file) {
        return false;
    }
}

组合设计模式遍历code
package com.tom.结构型设计模式;

import java.util.ArrayList;
import java.util.List;

public class ImitationComposite {
    public static void main(String[] args) {
        AbstractFile root = new Folder("root");
        AbstractFile folderA = new Folder("FolderA");
        AbstractFile folderC = new Folder("FolderC");
        AbstractFile folderD = new Folder("FolderD");
        AbstractFile fileA = new File("FileA");
        root.Add(folderA);
        root.Add(folderC);
        root.Add(folderD);
        root.Add(fileA);
    //        System.out.println(root.Add(folderA));
    //        System.out.println(root.Add(fileA));
        AbstractFile folderB = new Folder("FolderB");
        AbstractFile fileB = new File("FileB");
        folderA.Add(folderB);
        folderA.Add(fileB);
//        System.out.println(folderA.Add(folderB));
//        System.out.println(folderA.Add(fileB));
        print(root);
        //从root开始遍历,整个文件夹;


    }
    //未实现递归
//    static void print(AbstractFile file){
//        file.printName();
//        List<AbstractFile> Children = file.getChildren() ;
//        for(AbstractFile child : Children){
//            System.out.println(child.name);
//        }
//    }
    //实现递归到folderB
    static void print(AbstractFile file){
        file.printName();
        List<AbstractFile> Children = file.getChildren() ;
        if (Children == null) return;//在递归时遍历是否是文件File或者Folder为空,为空时返回print,直到遍历完整个List
        for(AbstractFile child : Children){
            //在第一次遍历List<AbstractFile>时取到了FolderA(FolderB,FileB)
            //再次递归遍历,当前child<->即FolderA
            print(child);
            //遍历打印出结果
        }
    }

}
abstract class AbstractFile{
   protected String name ;
   public void printName(){
       System.out.println(name);
   }
   public abstract boolean Add(AbstractFile file);
   public abstract boolean Delete(AbstractFile file);
   public abstract List getChildren();
}
class Folder extends AbstractFile{
    private List<AbstractFile> childLlsit = new ArrayList<AbstractFile> () ;
    public Folder(String name){
        this.name = name ;
    }

    @Override
    public boolean Add(AbstractFile file) {
        childLlsit.add(file);
        return true ;
    }

    @Override
    public boolean Delete(AbstractFile file) {
        childLlsit.remove(file);
        return true;
    }

    @Override
    public List<AbstractFile> getChildren() {
        return childLlsit;
    }
}
class File extends AbstractFile{
    public File (String name){
        this.name = name ;
    }

    @Override
    public boolean Add(AbstractFile file) {
        return false;
    }

    @Override
    public boolean Delete(AbstractFile file) {
        return false;
    }

    @Override
    public List<AbstractFile> getChildren() {
        return null;
    }
}

装饰器模式(Decorator)

image-20231023140258368


装饰器模式的适用性

image-20231023140401202


装饰器模式code
package com.tom.结构型设计模式;

public class ImitationDecorator {
    public static void main(String[] args) {
        Person zhangSan= new Student("张三");
        zhangSan.Operation();
        System.out.println("===================");
        zhangSan = new DecoratorA(zhangSan);
        zhangSan.Operation();
        System.out.println("===================");
        zhangSan = new DecoratorB(zhangSan);//再将张三加入DecoratorB时调用Operation()时的顺序是什么?
        zhangSan.Operation();//这条语句解释一下执行的顺序
        /**
         *1,整体在执行时,因为DecoratorA和 DecoratorB都是Decorator的子类,
         *2,这是子类父类在调用时的执行顺序吗?测试一下将DecoratorB写在前面的效果(根代码编写顺序无关)
         * 3,听讲理解(稍慢点)
         */
    }
}
abstract class Person{
    protected String name ;
    public abstract void Operation();//职责
}
class Student extends  Person{
    public Student (String name){
        this.name = name ;
    }
    @Override
    public void Operation(){
        System.out.print(name + ":职责为学习");
    }
}
abstract class Decorator extends Person{
 protected Person person ;
}
class DecoratorB extends Decorator{
    public DecoratorB(Person person){
        this.person = person ;
    }
    @Override
    public void Operation(){
        person.Operation();//原本的职责
        System.out.print("+健康");//职责
    }
}
class DecoratorA extends Decorator{
    public DecoratorA(Person person){
        this.person = person ;
    }
    @Override
    public void Operation(){
        person.Operation();//原本的职责
        System.out.print("+写作业");//职责
    }
}
//class DecoratorB extends Decorator{
//    public DecoratorB(Person person){
//        this.person = person ;
//    }
//    @Override
//    public void Operation(){
//        person.Operation();//原本的职责
//        System.out.print("+健康");//职责
//    }
//}

装饰器模式的执行思路zst_2001
/**
 *1,整体在执行时,因为DecoratorA和 DecoratorB都是Decorator的子类,
 *2,这是子类父类在调用时的执行顺序吗?测试一下将DecoratorB写在前面的效果(根代码编写顺序无关)
 * 3,听讲理解(稍慢点)
 * 4,叙述
 *  根据代码,DecoratorB(zhangSan)->这里的zhangSan是    public DecoratorA(Person person) {
 *         this.person = person;
 *     }执行        zhangSan = new DecoratorA(zhangSan);后的person
 *     所以在执行  B中的      person.Operation();//原本的职责->对应到A-> person.Operation()
 *     //即是先执行student中的Operation() ;2,再执行 DecoratorA中的   -》      System.out.print("+写作业");//职责
 *     //3,DecoratorB->        System.out.print("+健康");//职责
 */

image-20231023145614254


外观模式(Facade)

image-20231023163646076


外观模式的适用性

image-20231023163556108


(享元模式)Flyweight

共享地址?已有对象不用再创建,直接从地址中调用即可;

image-20231023164918710


享元模式的适用性

image-20231023165022693


享元模式code
Pieces
package com.tom.结构型设计模式;

public class ImitationFlyweight {
    public static void main(String[] args) {
        PieceFactory pieceFactory = new PieceFactory();
        piece whitePiece1 = pieceFactory.getPiece(0);
        System.out.println(whitePiece1);
        piece whitePiece2 = pieceFactory.getPiece(0);
        System.out.println(whitePiece2);
        piece blackPiece1 = pieceFactory.getPiece(1);
        System.out.println(blackPiece1);
        piece blackPiece2 = pieceFactory.getPiece(1);
        System.out.println(blackPiece2);
    }

}
class PieceFactory{
    private piece []  pieces = {new whitePiece(),new blackPiece()};
    public piece getPiece(int key){
        if(key == 0) return pieces[0];
        else return pieces[1];
    }
}
abstract class piece {
    protected String color ;
    public abstract void draw(int x , int y);
}
class whitePiece extends piece{
    public whitePiece(){
        this.color = "white" ;
    }
    @Override
    public void draw(int x, int y){
        System.out.println("draw a color : "+color+"piece x :"+x+"piece y :"+y);
    }
}
class blackPiece extends piece{
    public blackPiece(){
        this.color = "black" ;
    }
    @Override
    public void draw(int x, int y){
        System.out.println("draw a color : "+color+"piece x :"+x+"piece y :"+y);
    }
}

Circle
package com.tom.结构型设计模式;


import java.util.*;

public class ImitationFlyweight2 {


    public static void main(String[] args) {
        shapeFactory shapefactory = new shapeFactory();
        Random random = new Random();
        String[] colors = {"red","blue","yellow","grey","black","red"};
        for(int i = 0 ;i<=99 ; i++){
            int x = random.nextInt(colors.length);//[0-5]
            shape shapes = shapefactory.getShape(colors[x]);
            System.out.println("第" + i + "个圆");
            shapes.draw(random.nextInt(2023),random.nextInt(17));
        }
    }
}
class shapeFactory{
    private Map<String , shape> map= new HashMap<>();
    public shape getShape(String key){
        //未降重code
//        if(map.containsKey(key)){
//            return map.get(key);
//        }else{
//            shape shapes = new Circle(key);
//            map.put(key,shapes);
//            return map.get(key);
//        }
        //降重code
        if(!map.containsKey(key)){
            map.put(key,new Circle(key));
            System.out.println("create color : "+key+" circle");
        }
        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("draw a color : "+color+"  circle x:"+x+" y : "+ y);
    }
}

代理模式(Proxy)

image-20231023190624568


代理模式的适用性

image-20231023190533303


代理模式code
package com.tom.结构型设计模式;

public class ImitationProxy {
    public static void main(String [] args){
        RealSubject realSubject = new RealSubject();
        Proxy proxy = new Proxy(realSubject);
        proxy.buy();
    }
}
interface subject{
    public void buy();
}
class Proxy implements subject{

    protected RealSubject realSubject ;
    public Proxy(RealSubject realSubject){
        this.realSubject = realSubject ;
    }

    @Override
    public void buy(){
        System.out.println("办理前的手续");
        realSubject.buy();
        System.out.println("办理后的手续");
    }
}
class RealSubject implements subject{
    @Override
    public void buy(){
        System.out.println("付钱");
    }
}

行为型设计模式

image-20231023192241252


责任链模式(Chain of Responsibility)

image-20231023193147669


责任链模式的适用性

image-20231023193109596


责任链模式code
package com.tom.行为型设计模式;

public class ImitationChainOfResponsibility {
    public static void main(String [] args){
        Handler fuDaoYuan = new FuDaoYuan();
        Handler yuanZhang = new YuanZhang();
        Handler XiaoZhang = new HeadMaster();
        fuDaoYuan.setNext(yuanZhang);
        yuanZhang.setNext(XiaoZhang);
        fuDaoYuan.HandlerRequest(4);
    }
}
abstract class Handler{
    protected Handler next ;
    public void setNext(Handler next){
        this.next = next ;
    }
    public abstract void HandlerRequest(int request);
}
class FuDaoYuan extends Handler{
    @Override
    public void HandlerRequest(int request){
        if(request <= 7){
            System.out.println("辅导员审核通过");
        }else {
            if(next !=null){
                next.HandlerRequest(request);
            }else {
                System.out.println("审批无法通过");
            }
        }
    }
}

class YuanZhang extends Handler{
    @Override
    public void HandlerRequest(int request){
        if(request <= 15){
            System.out.println("院长审核通过");
        }else {
            if(next !=null){
                next.HandlerRequest(request);
            }else {
                System.out.println("审批无法通过");
            }
        }
    }
}

class HeadMaster extends Handler{
    @Override
    public void HandlerRequest(int request){
        if(request <= 30){
            System.out.println("校长审核通过");
        }else {
            if(next !=null){
                next.HandlerRequest(request);
            }else {
                System.out.println("审批无法通过");
            }
        }
    }
}

命令模式(Command)

image-20231023200011621


命令模式的适用性

image-20231023195934170


命令模式code
package com.tom.行为型设计模式;

public class ImitationCommand {
    public static void main(String[] args) {

        Tv tv = new Tv();
        Command ON = new OnCommand(tv);
        Command OFF= new OffCommand(tv);
        Invoker invoker = new Invoker();
        invoker.setCommand(ON);
        invoker.call();
        System.out.println("=================");
        invoker.setCommand(OFF);
        invoker.call();

    }
}

class Invoker{
    //请求者

    private Command command ; //命令
    public void setCommand (Command command){
        this.command = command ;
    }

    public void call(){
        command.Execute();
    }
}

interface Command{
    public void Execute();
}
class OffCommand implements Command{
    private Tv tv ;
    public OffCommand(Tv tv){
        this.tv = tv ;
    }
    @Override
    public void Execute(){
        tv.offAction();
    }

}

class OnCommand implements Command{
    private Tv tv ;

    public OnCommand(Tv tv){
        this.tv = tv ;
    }

    @Override
    public void Execute(){
    tv.onAction();
    }
}

class Tv{
    public void onAction(){
        System.out.println("开机行动");
    }
    public void offAction(){
        System.out.println("关机行为");
    }
}

解释器模式(Interpreter)

image-20231023204433062


解释器模式的适用性

image-20231023204358807


解释器模式code
package com.tom.行为型设计模式;

import java.util.HashSet;
import java.util.*;

public class ImitationInterpreter {
    public static void main(String[] args) {
        Context context = new Context();
        context .check("A区的开发人员");
        context.check("B区的开发人员");
        context.check("C区的开发人员");

        context.check("D区的开发人员");
    }
}
class Context{
    private String[] regions = {"A区","B区","C区"};
    private String[] persons = {"开发人员","测试人员","调试人员"};
    private NoTerminalExpression noTerminalExpression ;
    public Context(){
         TerminalExpression region = new TerminalExpression(regions);
         TerminalExpression person = new TerminalExpression(persons);
        noTerminalExpression = new NoTerminalExpression(region,person);

    }
    public void check(String info){
        boolean bool = noTerminalExpression.Interpret(info);
        if(bool){
            System.out.println("识别成功");
        }else {
            System.out.println("识别失败");
        }
    }

}

interface Expression{
    public boolean Interpret(String info);
}

class NoTerminalExpression implements Expression{

    private TerminalExpression region ;
    private TerminalExpression person;
    public NoTerminalExpression(TerminalExpression region , TerminalExpression person){
        this.person = person ;
        this.region = region ;
    }

    @Override
    public boolean Interpret(String info) {
        String[] str = info.split("的");
        return (region.Interpret(str[0])&&person.Interpret(str[1]));
    }
}

class TerminalExpression implements Expression{
    private Set<String> set = new HashSet<>();

    public TerminalExpression(String[] data){
        for(String str : data){
            set.add(str);
        }
    }

    @Override
    public boolean Interpret(String info){
        return set.contains(info);
    }
}

迭代器模式(Iterator)

image-20231024090214058


迭代器模式的适用性

image-20231024090239601


迭代器模式code
package com.tom.行为型设计模式;

import java.util.ArrayList;

import java.util.List;

public class ImitationIterator {
    public static void main(String[] args) {
        List<Book> bookList = new ArrayList<>();
        String[] books = {"水浒传", "三国演义", "红楼梦", "西游记"};
        double[] prices = {12, 1, 31, 231, 12341};
        //使用for循环和增强for循环遍历List并往List中添加元素
        for (int i = 0; i < 4; i++) {
            bookList.add(new Book(books[i], prices[i]));
        }
        for (int i = 0; i < bookList.size(); i++) {
            Book book = bookList.get(i);
            System.out.println(book.getName() + "  " + book.getPrice());
        }
        System.out.println("=======================");
        for (Book book : bookList) {
            System.out.println(book.getName() + "  " + book.getPrice());
        }
        System.out.println("=======================");
//        //使用迭代器遍历集合List
//        Iterator<Book> iterator = bookList.iterator();
//        while (iterator.hasNext()) {
//            //需要类型转换?
//            //最好是对应类型转换,
//        Book book =    (Book) iterator.next();
//        System.out.println(book.getName() + "  " + book.getPrice());
//
            System.out.println(iterator.next().getName()+"  "+iterator.next().getPrice());
//        }

        //你认为写完了吗?可以迭代成功BookList?try?
        BookAggregate bookAggregate = new BookAggregate();
        for (int i = 0; i < 4; i++) {
            bookAggregate.AddBook(new Book(books[i], prices[i]));
        }
//        BookIterator bookiterator = (BookIterator) bookAggregate.CreateIterator(bookAggregate);
        Iterator bookiterator = bookAggregate.CreateIterator();
        while (bookiterator.hasNext()){
            Book book = (Book) bookiterator.next();
            System.out.println(book.getName() + "  " + book.getPrice());

        }
    }
}

interface Iterator {
public boolean hasNext();
public Object next();
}
class BookIterator implements Iterator{
    private int index ;
    private BookAggregate bookAggregate ;

    public BookIterator(BookAggregate bookAggregate) {
        this.index = 0 ;
        this.bookAggregate = bookAggregate;
    }

    @Override
    public boolean hasNext(){
        if(index<bookAggregate.getSize()){
            return true;
        }else {
            return false;
        }

    }
    @Override
    public Object next(){
      Object obj  =   bookAggregate.get(index);
      index++;
      return obj ;

    }
}

interface Aggregate{
    public Iterator CreateIterator();
}
class BookAggregate implements Aggregate{
    private  List<Book> bookList = new ArrayList<>();
    public void AddBook(Book book){
        bookList.add(book);
    }
    public Book get(int index){
      return   bookList.get(index);
    }
    public int getSize(){
        return bookList.size();
    }

//    @Override
//    public Iterator CreateIterator() {
//        return new BookIterator();
//    }


//    @Override
//    public Iterator CreateIterator(BookAggregate bookAggregate) {
//        return new BookIterator(bookAggregate);
//    }

    @Override
    public Iterator CreateIterator() {
        return new BookIterator(this);
    }
}


class Book {
    private String name;
    private double price;

    public Book() {
    }

    public Book(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

中介者模式(Meditor)

image-20231024102641112


中介者模式适用性

image-20231024100435361


中介者模式的code
package com.tom.行为型设计模式;

public class ImitationMeditor {
    public static void main(String[] args){
        ConcreteMeditor concreteMeditor = new ConcreteMeditor();
        Colleague1 colleague1 = new Colleague1(concreteMeditor);
        Colleague2 colleague2 = new Colleague2(concreteMeditor);
        concreteMeditor.setColleague1(colleague1);
        concreteMeditor.setColleague2(colleague2);
        colleague1.sendMessage("messageASD");//空指针异常
        colleague2.sendMessage("messageZXC");

    }
}
abstract class Colleague{
    protected Meditor meditor ;
}

class Colleague1 extends Colleague{
    public Colleague1 (Meditor meditor){
        this.meditor = meditor ;
    }
    public void sendMessage(String message){
        meditor.sendMessage(message,this);
    }

    public void Notify(String message){
        System.out.println("同事1收到同事2发送的" + message);
    }
}
class Colleague2 extends Colleague{
    public Colleague2 (Meditor meditor){
        this.meditor = meditor ;
    }
    public void sendMessage(String message){
        meditor.sendMessage(message,this);
    }

    public void Notify(String message){
        System.out.println("同事2收到同事1发送的" + message);
    }
}


abstract class Meditor{
    public abstract void sendMessage(String Message ,Colleague colleague);

}
class ConcreteMeditor extends Meditor {
    private Colleague1 colleague1 ;
    private Colleague2 colleague2 ;
    public void setColleague1 (Colleague1 colleague1){
        this.colleague1 = colleague1 ;
    }
    public void setColleague2(Colleague2 colleague2){
        this.colleague2 = colleague2 ;
    }

    @Override
    public void sendMessage(String Message, Colleague colleague) {
    if (colleague == colleague1){
            colleague2.Notify(Message);
    }else {
            colleague1.Notify(Message);
    }
    }
}

备忘录模式(Memento)

image-20231024112233581


备忘录模式的适用性

image-20231024112151523


备忘录模式code
package com.tom.行为型设计模式;

import java.util.ArrayList;
import java.util.List;

public class ImitationMemento {
    public static void main(String [] args){
        Originator originator = new Originator();
        Caretaker caretaker = new Caretaker();
        originator.setState("500");
        Memento memento1 = originator.createMemento();
        caretaker.addMemento(memento1);
        originator.setState("404");
        Memento memento2 = originator.createMemento();
        caretaker.addMemento(memento2);
        originator.setState("200");
        Memento memento3 = originator.createMemento();
        caretaker.addMemento(memento3);
        System.out.println(caretaker.getMemento(1).getState() );
        caretaker.showMemento();


//        Memento memento = new Memento();
    }
}
class Originator{
    private String state ;

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }
    public Memento createMemento(){
        return new Memento(state);
    }

    public void setMemento(Memento memento){
        state = memento.getState();
    }
}
class Memento{
    private String state ;

    public Memento(String state) {
        this.state = state;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

}

class Caretaker{
    private List<Memento> mementoList = new ArrayList<>();
    public void addMemento(Memento memento){
        mementoList.add(memento);
    }
    public Memento getMemento(int index){
        return mementoList.get(index-1);
    }
    public void showMemento(){
        int cnt = 1 ;
        for(Memento memento : mementoList){
            System.out.println("第"+cnt+"次备份的状态为"+memento.getState());
            cnt++;
        }
    }
}

观察者模式(Observer)

image-20231024134657455


观察者模式的适用性

image-20231024134617604


观察者模式code
package com.tom.行为型设计模式;

import java.util.ArrayList;
import java.util.List;

public class ImitationObserver {
    public static void main(String [] args){
        Subject subjectA = new ConcreteSubject("目标A");
         Observer zhangSan = new ConcreteObserver("张三", subjectA);
         Observer LiSi = new ConcreteObserver("李四",subjectA);
         Observer WangWu = new ConcreteObserver("王五",subjectA);
         subjectA.setState("更新了");
        subjectA.Notify();
    }
}
interface Subject{
    public void Attach(Observer observer);
    public void Detach(Observer observer);
    public void Notify();//更新通知
    public void setState(String state) ;
    public String getState();
}
class ConcreteSubject implements Subject{
    private String name ;
    private String state;
    private List<Observer> observerList ;
    public void setState(String state){
        this.state = state ;
    }
    public String getState(){
        return state ;
    }
    public ConcreteSubject(String name) {
        this.name = name ;
        state = "未更新" ;
     observerList =   new ArrayList<Observer>() ;
    }

    @Override
    public void Attach(Observer observer) {
    observerList.add(observer);
    }

    @Override
    public void Detach(Observer observer) {
    observerList.remove(observer);
    }

    @Override
    public void Notify() {
        //更新通知
        for(Observer observer : observerList){
                observer.update();
        }
    }
}
interface Observer{
    public void update();
}
class ConcreteObserver implements Observer{
    private String state ;
    private String name;
    private Subject subject ;

    public ConcreteObserver(String name, Subject subject) {
        this.name = name;
        this.subject = subject;
        subject.Attach(this);
        state = subject.getState();
    }

    @Override
    public void update() {
        System.out.println(name+"收到通知");
        state = subject.getState();
        System.out.println(name+"改变后的状态为:"+state);
    }
}

状态模式(State)

image-20231024144013145


状态模式的适用性

image-20231024143938629


状态模式code
package com.tom.行为型设计模式;

public class ImitationState {
    public static void main(String[] args) {
        Context2 context2 = new Context2();
        System.out.println(context2.getStates());
        context2.request();//购买一个饮料count = 2 ;
        context2.request();;//购买一个饮料count = 1 ;
        context2.request();//count = 0 ;
        System.out.println(context2.getStates());//卖光了,将状态设置为StateB
        context2.request();
    }
}
class Context2{
    //贩卖机
    private int count ;
    private state states ;
    public Context2(){
        count = 3;
        states =  new StateA();
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public state getStates() {
        return states;
    }

    public void setStates(state states) {
        this.states = states;
    }
    public void request(){
        states.Handle(this);
    }


}
interface state{
    public void Handle(Context2 context2);
}
class StateA implements state{//有货

    @Override
    public void Handle(Context2 context2) {
        int count = context2.getCount();
        if(count >= 1){
            System.out.println("购买成功");
            context2.setCount(count-1);
            if(context2.getCount() == 0){
                context2.setStates(new StateB());
            }
        }else {
            System.out.println("购买失败");
        }

    }
}
class StateB implements state{//无货

    @Override
    public void Handle(Context2 context2) {
        int count = context2.getCount();
        if(count == 0){
            System.out.println("购买失败! 等待补货");
        }

    }
}

策略模式(Strategy)

image-20231024184121679


策略模式的适用性

image-20231024184224313


策略模式code
package com.tom.行为型设计模式;

public class ImitationStrategy {
    public static void main(String[] args) {

        Strategy add= new AddStrategy();
        Strategy substract =new SubtractionStrategy();
        Strategy MULTIPLY = new MultiplyStrategy();
        OperationContext operationContext = new OperationContext(add);
        operationContext.Operation(12,12);
        OperationContext operationContext1 = new OperationContext(substract);
        operationContext1.Operation(12,1);
        OperationContext operationContext2 =new OperationContext(MULTIPLY);
        operationContext2.Operation(123,123);


    }
}
class OperationContext{
    private Strategy strategy ;

    public OperationContext(Strategy strategy) {
        this.strategy = strategy;
    }
    public void Operation(int a, int b){
        strategy.TwoNumberOperation(a,b);
    }

}
interface Strategy{
    public void TwoNumberOperation(int a ,int b);
}
class AddStrategy implements Strategy{

    @Override
    public void TwoNumberOperation(int a, int b) {
        System.out.println(a+b);
    }
}
class SubtractionStrategy implements Strategy{

    @Override
    public void TwoNumberOperation(int a, int b) {

        System.out.println(a-b);

    }
}
class MultiplyStrategy implements Strategy{

    @Override
    public void TwoNumberOperation(int a, int b) {
        System.out.println(a*b);
    }
}

模版方法模式(Template Method)

image-20231024190454721


模版方法模式的适用性

image-20231024190358814


模版方法模式code
package com.tom.行为型设计模式;

public class ImitationTemplateMethod {
    public static void main(String[] args) {
        Person student = new Student();
        Person teacher = new Teacher();
        student.TemplateMethod();

        System.out.println("==========================");

        teacher.TemplateMethod();
    }
}
abstract class Person{
    public void TemplateMethod(){
        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("教师:批改作业");
    }
}

访问者模式(Visitor)

image-20231024195322789


访问者模式的适用性

image-20231024195453382


访问者模式code
package com.tom.行为型设计模式;

import java.util.ArrayList;
import java.util.List;

public class ImitationVisitor {
    public static void main(String[] args) {
        PersonStructure personStructure = new PersonStructure();
        Visitor1 visitor1 = new Visitor1();
        System.out.println("访问者1的访问记录");
        personStructure.Accept(visitor1);
        double maxScore = visitor1.getMaxScore();
        System.out.println("最大成绩:"+maxScore);
        int maxWorkYear = visitor1.getMaxWorkYear();
        System.out.println("最大工龄:"+maxWorkYear);

        System.out.println("============================");

        Visitor2 visitor2 = new Visitor2();
        System.out.println("访问者2的访问记录");
        personStructure.Accept(visitor2);
    }

}
interface visitor{
    public void visitStudent(Student1 student1);
    public void visitTeacher(Teacher1 teacher1);
}
class Visitor1 implements visitor{
    private double maxScore = -1 ;
    private int maxWorkYear = -1 ;

    public double getMaxScore() {
        return maxScore;
    }

    public void setMaxScore(double maxScore) {
        this.maxScore = maxScore;
    }

    public int getMaxWorkYear() {
        return maxWorkYear;
    }

    public void setMaxWorkYear(int maxWorkYear) {
        this.maxWorkYear = maxWorkYear;
    }

    @Override
    public void visitStudent(Student1 student1) {
        System.out.println("访问者2访问学生"+student1.getName()+"/年龄:"+student1.getAge()+"/成绩"+student1.getScore());
        maxScore = Math.max(maxScore,student1.getScore());
    }

    @Override
    public void visitTeacher(Teacher1 teacher1) {
        System.out.println("访问者2访问老师"+teacher1.getName()+"/年龄"+teacher1.getAge()+"/工龄"+teacher1.getWorkYear());
    maxWorkYear = Math.max(maxWorkYear,teacher1.getWorkYear());
    }
}

class Visitor2 implements visitor{
    private double maxScore = -1 ;
    private int maxWorkYear = -1 ;

    public double getMaxScore() {
        return maxScore;
    }

    public void setMaxScore(double maxScore) {
        this.maxScore = maxScore;
    }

    public int getMaxWorkYear() {
        return maxWorkYear;
    }

    public void setMaxWorkYear(int maxWorkYear) {
        this.maxWorkYear = maxWorkYear;
    }

    @Override
    public void visitStudent(Student1 student1) {
        System.out.println("访问者2访问学生"+student1.getName()+"/年龄:"+student1.getAge()+"/成绩"+student1.getScore());
        maxScore = Math.max(maxScore,student1.getScore());

    }

    @Override
    public void visitTeacher(Teacher1 teacher1) {
        System.out.println("访问者2访问老师"+teacher1.getName()+"/年龄"+teacher1.getAge()+"/工龄"+teacher1.getWorkYear());
        maxWorkYear = Math.max(maxWorkYear,teacher1.getWorkYear());

    }
}
abstract class Person1{
    private String name ;
    private int age ;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Person1(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public abstract void Accept(visitor visitors);

}
class Student1 extends Person1{
    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }

    private double score ;
    public Student1(String name,int age ,double score) {
        super(name,age);
        this.score = score ;
    }

    @Override
    public void Accept(visitor visitors) {
        visitors.visitStudent(this);
    }
}
class Teacher1 extends Person1{

    public int getWorkYear() {
        return workYear;
    }

    public void setWorkYear(int workYear) {
        this.workYear = workYear;
    }

    private int workYear ;
    public Teacher1(String name,int age,int workYear){
        super(name,age);
        this.workYear = workYear ;
    }
    @Override
    public void Accept(visitor visitors) {
        visitors.visitTeacher(this);
    }
}
class PersonStructure{
    private List<Person1> person1List = new ArrayList<>();

    public PersonStructure() {
       person1List.add(new Student1("张三",10,77));
        person1List.add(new Student1("李四",11,78));
        person1List.add(new Student1("王明",12,79));
        person1List.add(new Student1("张三二号",13,80));
        person1List.add(new Teacher1("老王",30,3));
        person1List.add(new Teacher1("苍合",40,4));
        person1List.add(new Teacher1("yupi",20,2));
        person1List.add(new Teacher1("小布",18,1));
    }
    public void Accept(visitor visitors){
    for(Person1 person1 : person1List){
        person1.Accept(visitors);
    }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值