zst_2001B站软考-下午题知识点笔记简

# **软考下午题**

一大题知识点

数据流图

数据流程图基本元素

image-20231016134504519


外部实体的基本定义

image-20231016134747298


数据存储的基本定义

image-20231016135130154


加工的基本定义

image-20231016135449153


数据流的基本定义

image-20231016135742580


问题1(找出外部实体)

image-20231016142118701


示例

image-20231016161323604


问题1答题格式

示例

E1 : 客户

问题2(找出数据存储)

image-20231016161635494


示例:

image-20231016164219863


问题1答题格式

示例

D1:销售订单表

问题3(找出数据流中的起点和终点)

image-20231016164334681


做题方法一(父图子图平衡)

父图和子图找不同的看同一数据流是否一样(一样就划去过滤),未一样看是否缺失数据流

image-20231016165353797


做题方法二(加工既有输入数据流也有输出数据流)

image-20231016170042716


image-20231016170132469

必须满足加工至少有一个输入数据流和至少有一个输出数据流,否则就缺数据流


做题方法三(数据守恒)

image-20231016170814127

图文匹配,是否缺失数据流


答题格式

缺失数据流(起点或终点必须有一个是加工);否则错误

image-20231016171256747


二大题知识点

E-R图基本图形元素

实体

image-20231021180907175


弱实体

image-20231021181038356


属性

image-20231021181121647


联系
两个实体之间的联系

image-20231021181223108


三个实体之间的联系

image-20231021181358831


关系模式和主外键

image-20231021193258487


www.phind.com解惑?

外键一定是别的表的主键吗

外键 不一定 是 别的表的主键

ANSWER | PHIND V6 MODEL

外键并不一定是别的表的主键。虽然在大多数情况下,外键通常是指向另一个表的主键,但这并不是强制的。实际上,外键可以是另一个表中的任何唯一键,不一定是主键zhuanlan.zhihu.com

例如,假设我们有两个表,一个是 dc_standard,一个是 dc_soil。在 dc_standard 表中有一个 id 字段,但这个字段不是主键。在 dc_soil 表中有一个 dc_standard_id 字段,我们想把 dc_standard_id 设置为外键,关联 dc_standard 表的 id。这种情况下,我们需要先把 dc_standard 表的 id 设置为唯一键,然后再设置外键zhuanlan.zhihu.com

外键的主要目的是控制可以存储在外键表中的数据,并控制对主键表中数据的更改。例如,如果在 Sales.SalesPerson 表中删除一个销售人员行,而这个销售人员的 ID 由 Sales.SalesOrderHeader 表中的销售订单使用,则这两个表之间关联的完整性将被破坏。外键约束防止这种情况发生。如果主键表中数据的更改使之与外键表中数据的链接失效,则这种更改将无法实现,从而确保了引用完整性cnblogs.com

总的来说,虽然外键通常指向另一个表的主键,但这并不是必须的。外键可以是另一个表中的任何唯一键,只要这个键的值在另一个表中是唯一的,就可以作为外键。


关系模式联系转换
一对一转换

image-20231021193715359


一对多转换

image-20231021193753943


多对多转换

image-20231021193822556


三个实体之间的联系转换

image-20231021193910173


超类子类转换

image-20231021193945590


当出现联系之间的联系时(聚合实体)

image-20231022144847805


三大题知识点

UML类图

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-20231029193926556


N皇后问题

image-20231029195046097


image-20231029195115819


源imtationQueensCode
//
// Created by GER on 2023/10/29.
//
#include <stdio.h>
#include <math.h>
//使用一维数组存储NXN的表盘
//a[i] 表示第i个皇后在第i行第a[i]列;
#define N 4 //棋盘的大小-当前为4X4
int q[N+1];//存储皇后的序号,这里皇后的序列只使用1,2,3,4,序号为0的不使用
int check(int j){
    //检查第j个皇后的位置是否合法,判断两个皇后是否在同一列
    //并且判断qi行-qj行的绝对值是否等于q[i]列-q[j]列的绝对值-即是判断当前两个皇后是否在对角线上
    int i ;
    for(i=1;i<j;i++){//只要满足一个就不能在这个位置放置皇后
        if(q[i] == q[j]||abs(i-j) == abs(q[i]-q[j])){
            return 0;//返回0是指未满足N皇后棋盘原则;
        }
    }
    return 1;
}

void queen(){
    //求解N皇后方案
    int i ;
    for(i=1;i<=N;i++){
        q[i]=0;//遍历整个棋盘?,先将全部皇后的初值赋值为0?
    }
    int answer = 0 ;//方案数;
    int j = 1;//表示正在摆放的皇后;(这里从第一个皇后开始)
    while (j >= 1) {
        q[j] = q[j] + 1;//让第j个皇后往后一列摆放,(初始为第一个皇后摆放在第一行第一列)
        while (q[j] <= N && !check(j)) {//判断第j个皇后的位置是否合法
            // !check(j)因为check(j)在判断时如果未满足N皇后规则就返回为0即false
            // !check(j)->为true时即->check(j)为0->未满足N皇后规则
            q[j] = q[j] + 1;//不合法就往后一个摆放
        }
        if(q[j] <= N){//判断当前列是否越界,并且表示第j个皇后找到了一个合法的摆放位置
            if(j == N){
                //找到了N皇后的一组解
                answer = answer + 1;
                printf("方案%d: ",answer);
                for(i= 1; i<=N;i++){
                    printf("%d ",q[i]);
                }
                printf("\n");
            }else{
                j = j+1;//继续摆放下一个皇后

            }


        }else{//表示第j个皇后找不到一个合法的摆放位置
            q[j]=0;//还原第j个皇后的位置
            j=j-1;//回溯

        }

    }

}
int main(){
    //是代码问题出现乱码吗?
    queen();
    return 0 ;
}

ImitaionErrorCodeCorrection
//
// Created by GER on 2023/10/30.
//
#include <stdio.h>
#include <math.h>
//先定义棋盘的大小,假设4X4;
#define N 4
//用一维数组来表示棋盘大小,
int q[N+1];//这里只使用下标为1,2,3,4的数组值来表示棋盘中的皇后
//q[i]表示第i个皇后在第i行第q[i]列
//编写方法判断摆放位置是否合法
int check(int j){
    //传入需要摆位置的第j个皇后,判断第j个位置的皇后是否合法
    int i ;
    for(i=1;i<j;i++){
        //遍历当前列是否和需要摆的当前皇后的列相等,或者判断两个皇后是否在斜线上
        if(q[i] == q[j] || abs(i-j) == abs(q[i]-q[j])) {
            return 0;//返回0是指当前未满足N皇后摆放规则
        }
    }
    return 1;
}
void queen(){
    //编写当前N皇后的回溯问题,从第一个皇后开始摆放,直到摆放当前设定的4个皇后
    int i ;
    int j = 1;//先设定从第从第一个开始摆放
    int answer = 0;
    //将棋盘中所有皇后赋值初值都为0
    for(i = 1;i<=N;i++){
        q[i]=0;
    }
    //开始摆放第一个皇后
//    while (j<=N){//先判断当前摆放的皇后是否数组越界
    while (j>=1){//这里?
        //开始摆放
        //先将第一个皇后摆放在第一行第q[j]列
        q[j]=q[j]+1;//?
//        for(i=1;i<=N;i++){//为什么要这样写?
            //从第一个,皇后开始遍历
//            if(j<=N&&!check(j)){//这里开始回溯//过第一个一遍
        while (q[j]<=N && !check(j)){
                //j<=N表示判断数组是否越界
                // !check(j),判断当前摆放的位置是否符合N皇后摆放的位置
                // check(j)返回为0表示不满足当前位置,!check(j)->return 1 ;表示要开始往后摆放
                q[j]=q[j]+1;
            }
//            else{
//                j=j+1;//摆放下一个皇后
//            }
            //这里在摆第三个皇后时需要开始回溯

//        }
        //判断当前摆放的位置是否已找到最优解
        if(q[j]<=N) {1
            if (j == N) {
                //表示已经找到一组最优解
                answer = answer + 1;
                printf("方案%d ", answer);
                for (i = 1; i <= N; i++) {
                    printf("%d", q[i]);

                }
                printf("\n");
            } else{
                j = j+1;
            }
//            else {
//                q[j] = 0;
//                j = j - 1;
//            }

        }else {
            q[j] = 0;
            j = j - 1;
        }

    }
}
int main(){
    queen();
    return 0;
}

ErroCode
//
// Created by GER on 2023/10/30.
//
#include <stdio.h>
#include <math.h>
//先定义棋盘的大小,假设4X4;
#define N 4
//用一维数组来表示棋盘大小,
int q[N+1];//这里只使用下标为1,2,3,4的数组值来表示棋盘中的皇后
//q[i]表示第i个皇后在第i行第q[i]列
//编写方法判断摆放位置是否合法
int check(int j){
    //传入需要摆位置的第j个皇后,判断第j个位置的皇后是否合法
    int i ;
    for(i=1;i<j;i++){
        //遍历当前列是否和需要摆的当前皇后的列相等,或者判断两个皇后是否在斜线上
        if(q[i] == q[j] || abs(i-j) == abs(q[i]-q[j])) {
            return 0;//返回0是指当前未满足N皇后摆放规则
        }
    }
    return 1;
}
void queen(){
    //编写当前N皇后的回溯问题,从第一个皇后开始摆放,直到摆放当前设定的4个皇后
    int i ;
    int j = 1;//先设定从第从第一个开始摆放
    int answer = 0;
    //将棋盘中所有皇后赋值初值都为0
    for(i = 1;i<=N;i++){
        q[i]=0;
    }
    //开始摆放第一个皇后
    while (j<=N){//先判断当前摆放的皇后是否数组越界
        //开始摆放
        //先将第一个皇后摆放在第一行第q[j]列
        q[j]=q[j]+1;//?
//        for(i=1;i<=N;i++){//为什么要这样写?
            //从第一个,皇后开始遍历
            if(j<=N&&!check(j)){//这里开始回溯//过第一个一遍
                //j<=N表示判断数组是否越界
                // !check(j),判断当前摆放的位置是否符合N皇后摆放的位置
                // check(j)返回为0表示不满足当前位置,!check(j)->return 1 ;表示要开始往后摆放
                q[j]=q[j]+1;
            } else{
                j=j+1;//摆放下一个皇后
            }
            //这里在摆第三个皇后时需要开始回溯

//        }
        //判断当前摆放的位置是否已找到最优解
        if(j==N){
            //表示已经找到一组最优解
            answer = answer + 1;
            printf("方案%d ",answer);
            for (i = 1;  i <=N ; i++) {
                printf("%d",q[i]);

            }
            printf("\n");
        } else{
            q[j]=0;
            j=j-1;
        }

    }
}
int main(){
    queen();
    return 0;
}

debug错1

image-20231030144419056



错2
if(q[j]<=N&&!check(j)){//啊while和if区别这么大的吗?
    //check(j)->0是表示当前不满足N皇后摆放规则,需要往后摆放
    // !check(j)->返回1执行往后摆放
    q[j]=q[j]+1;

}

***
while(q[j]<=N&&!check(j)){//啊while和if区别这么大的吗?
    //check(j)->0是表示当前不满足N皇后摆放规则,需要往后摆放
    // !check(j)->返回1执行往后摆放
    q[j]=q[j]+1;

}

这两段的区别是什么?

N皇后问题中(回溯什么时候结束)

 while (j>=1){//这里?
 
 
 }
 当回溯到第一行时,并且回溯到第一行最后一列再加一,继续判断是否满足,因已经超出棋盘数组的大小,
  q[j]=0;
  j=j-1;
  //第一行执行后,j=0;while循环结束回溯,全部N皇后方案已经找到;

N皇后问题(递归)

code
//
// Created by GER on 2023/10/30.
//

//N皇后问题(递归版)
#include <stdio.h>
#include <math.h>
//先定义棋盘的大小,假设4X4;
#define N 4
int answer = 0;
//用一维数组来表示棋盘大小,
int q[N+1];//这里只使用下标为1,2,3,4的数组值来表示棋盘中的皇后
//q[i]表示第i个皇后在第i行第q[i]列
//编写方法判断摆放位置是否合法
int check(int j){
    //传入需要摆位置的第j个皇后,判断第j个位置的皇后是否合法
    int i ;
    for(i=1;i<j;i++){
        //遍历当前列是否和需要摆的当前皇后的列相等,或者判断两个皇后是否在斜线上
        if(q[i] == q[j] || abs(i-j) == abs(q[i]-q[j])) {
            return 0;//返回0是指当前未满足N皇后摆放规则
        }
    }
    return 1;
}
void queen(int j){
    //将要摆放的皇后的位置传入
    int i ;
    for( i=1 ; i<=N ; i++){
        q[j]=i;//这里将一行中的各个位置遍历,依次判断是否符合位置
        if(check(j)){//判断当前摆放的位置是否合法
            if (j == N) {
                //表示已经找到一组最优解
                answer = answer + 1;
                printf("方案%d ", answer);
                for (i = 1; i <= N; i++) {
                    printf("%d", q[i]);

                }
                printf("\n");
            }else{
                queen(j+1);//递归摆放下一个皇后的位置
            }
        }
    }
}
int main(){
    queen(1);
    return 0;
}

分治法

分治法的基本思想

image-20231030202654493


六大题知识点

创建型设计模式

简单工厂模式

image-20231031200028882


简单工厂模式Code
package com.tom.创建型设计模式;

public class ImitationSimpleFactory {
    public static void main(String[] args) {
        Product A = Factory.createProduct("A");
        A.info();
        Product B = Factory.createProduct("B");
        B.info();
    }
}
class Factory{
    public static Product createProduct (String type) {
        Product product = null;
        switch(type){
            case "A":
                product = new ProductA();
                break;
            case "B":
                product = new ProductB();
                break;
            default:
                System.out.println("没有"+type+"类型的产品");
                break;

        }
        return product ;
    }
}
abstract class Product {
    public abstract void info();
}
class ProductA extends Product{

    @Override
    public void info() {
        System.out.println("产品的信息: A");
    }
}
class ProductB extends Product{

    @Override
    public void info() {
        System.out.println("产品的信息: B");
    }
}

工厂方法模式

image-20231031200921960


FactoryMethodCode
package com.tom.创建型设计模式;

public class ImitationFactoryMethod {
    public static void main(String[] args) {
        FactoryA factoryA = new FactoryA();
        Product1 productA = factoryA.createProduct1();
        productA.info();
        FactoryB factoryB = new FactoryB();
        Product1 productB = factoryB.createProduct1();
        productB.info();
    }
}
interface Product1{
    public void info();
}

class ProductA1 implements Product1 {


    @Override
    public void info() {
        System.out.println("产品的信息: A");
    }
}

class ProductB1 implements Product1 {


    @Override
    public void info() {
        System.out.println("产品的信息: B");
    }
}

interface Factory1{
    public Product1 createProduct1();
}
class FactoryA implements Factory1{

    @Override
    public Product1 createProduct1() {
        return new ProductA1();
    }
}
class FactoryB implements Factory1{

    @Override
    public Product1 createProduct1() {
        return new ProductB1();
    }
}

抽象工厂模式

image-20231031202818768


抽象工厂模式code
package com.tom.创建型设计模式;

public class ImitationAbstractFactory {
    public static void main(String[] args) {
        Factory2A factory2A = new Factory2A();
        ProductA21 productA21 = factory2A.createProductA21();
        ProductB21 productB21 = factory2A.createProductB21();
        productA21.info();
        productB21.info();

        Factory2B factory2B = new Factory2B();
        ProductA21 productA211 = factory2B.createProductA21();
        ProductB21 productB211 = factory2B.createProductB21();
        productA211.info();
        productB211.info();

    }

}
interface Factory2{
    public ProductA21 createProductA21();
    public ProductB21 createProductB21();

}
class Factory2A implements Factory2{
    public ProductA21 createProductA21(){
        return new ProductA21();
    };
    public ProductB21 createProductB21(){
        return new ProductB21();
    };
}
class Factory2B implements Factory2{
    public ProductA21 createProductA21(){
        return new ProductA21();
    };
    public ProductB21 createProductB21(){
        return new ProductB21();
    };
}


interface ProductA2{
    public void info();
}
interface ProductB2{
    public void info();

}
class ProductA21 implements ProductA2{

    @Override
    public void info() {
        System.out.println("产品信息A21");
    }
}
class ProductB21 implements ProductB2{

    @Override
    public void info() {
        System.out.println("产品信息B21");
    }
}

生成器模式

image-20231031211349295


生成器模式code
package com.tom.创建型设计模式;

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

public class ImitationBuilder {
    public static void main(String[] args) {
        Director director = new Director();
        Builder1 builder1 = new Builder1();
        director.Construct(builder1);
        ProductA3 productA3 = builder1.getResult();
        productA3.show();

        Builder2 builder2 = new Builder2();
        director.Construct(builder2);
        ProductA3 productA31 = builder2.getResult();
        productA31.show();
    }
}
class Director{
    public void Construct(Builder builder){
        builder.BuildPart();
    }
}
abstract class Builder{
    public abstract void BuildPart();
    public abstract ProductA3 getResult();
}
class Builder1 extends Builder{
        ProductA3 productA3 = new ProductA3();
    @Override
    public void BuildPart() {
        productA3.Add("A");
        productA3.Add("B");
        productA3.Add("C");
        productA3.Add("D");
        productA3.Add("E");
        productA3.Add("F");
    }

    @Override
    public ProductA3 getResult() {
        return productA3;
    }
}
class Builder2 extends Builder{
    ProductA3 productA3 = new ProductA3();
    @Override
    public void BuildPart() {
        productA3.Add("A");
        productA3.Add("B");
        productA3.Add("C");
        productA3.Add("D");
        productA3.Add("E");
        productA3.Add("F");
    }

    @Override
    public ProductA3 getResult() {
        return productA3;
    }
}
class ProductA3{
List<String> parts   =    new ArrayList<String>();
public void Add(String part){
    parts.add(part);
}
public void show(){
    System.out.println("产品的组成:");
    for(String s : parts)
        System.out.println(s+" ");

    System.out.println("\n");
}
}

原型模式

image-20231031215629270


原型模式code
package com.tom.创建型设计模式;

public class ImitationPrototype02 {
    public static void main(String[] args) {
        Product002 product002 = new Product002(1, 12);
        Product002 clone02 = (Product002)product002.clone02();
        System.out.println(product002.getId()+" "+product002.getPrice());
        System.out.println(clone02.getId()+" "+clone02.getPrice());
    }
}
interface Prototype02{
    public Object clone02();
}
class Product002 implements Prototype02{

    private int id ;
    private int price;

    public Product002() {
    }

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

    public int getId() {
        return id;
    }

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

    public int getPrice() {
        return price;
    }

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

    @Override
    public Object clone02() {
        Product002 product002 = new Product002() ;
        product002.id = this.id;
        product002.price = this.price;
        return product002 ;
    }
}

结构型设计模式

适配器模式

image-20231031233505613


适配器模式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-数据线");
    }
}

桥接模式

image-20231031235417744


桥接模式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.setName("产品A");
        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+ ": 蓝色 ");
    }
}

组合模式

image-20231101091812924


组合模式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;
    }
}

装饰器模式

image-20231101095751053


装饰器模式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,听讲理解(稍慢点)
         * 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("+健康");//职责
         */
    }
}

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("+健康");//职责
//    }
//}

享元模式

调用时从同一地址拿出->实现共享数据源?

image-20231101104009740


享元模式Code
List
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);
    }
}

Map
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);
    }
}

行为设计模式

命令模式

image-20231101105616105


命令模式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("关机行为");
    }
}

观察者模式

image-20231101111355102


观察者模式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);
    }
}

状态模式

image-20231101114012786


状态模式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("购买失败! 等待补货");
        }

    }
}

策略模式

image-20231101182110481


策略模式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);
    }
}

访问者模式

image-20231101201303324


访问者模式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("访问者1访问学生"+student1.getName()+"/年龄:"+student1.getAge()+"/成绩"+student1.getScore());
        maxScore = Math.max(maxScore,student1.getScore());
    }

    @Override
    public void visitTeacher(Teacher1 teacher1) {
        System.out.println("访问者1访问老师"+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);
    }
    }
}

中介者模式

image-20231101203631362


中介者模式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);
    }
    }
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值