设计模式(java版)——行为型——访问者模式

项目源码已提交github:https://github.com/ckl001/designPattem_java

package com.Ljava.design.pattem.behavioral.visitor;

/**
 * @Auther 20173
 * @Date 2019-4-15 14:26
 * @Des TODO
 **/
public abstract class Course {
    private String name;

    public String getName() {
        return name;
    }

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

    public abstract void accept(IVisitor iVisitor);
}

package com.Ljava.design.pattem.behavioral.visitor;

/**
 * @Auther 20173
 * @Date 2019-4-15 14:27
 * @Des TODO
 **/
public interface IVisitor {

    void  visit(FreeCourse freeCourse);

    void  visit(CodingCourse codingCourse);
}

package com.Ljava.design.pattem.behavioral.visitor;

/**
 * @Auther 20173
 * @Date 2019-4-15 14:32
 * @Des 访问者
 **/
public class Visitor implements IVisitor {
    //访问免费课程,打印所有免费课程名称
    @Override
    public void visit(FreeCourse freeCourse) {
        System.out.println("免费课程:"+freeCourse.getName());
    }

    //访问实战课程,打印所有实战课程名称及价格
    @Override
    public void visit(CodingCourse codingCourse) {
        System.out.println("实战课程:"+codingCourse.getName()+" 价格:"+codingCourse.getPrice()+"元");
    }

}

package com.Ljava.design.pattem.behavioral.visitor;

/**
 * @Auther 20173
 * @Date 2019-4-15 14:30
 * @Des 实战课程 收费
 **/
public class CodingCourse extends Course {
    private int price;

    public int getPrice() {
        return price;
    }

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

    @Override
    public void accept(IVisitor visitor) {
        visitor.visit(this);
    }
}

package com.Ljava.design.pattem.behavioral.visitor;

/**
 * @Auther 20173
 * @Date 2019-4-15 14:29
 * @Des 免费课程
 **/
public class FreeCourse extends Course{
    @Override
    public void accept(IVisitor visitor) {
        visitor.visit(this);
    }
}

package com.Ljava.design.pattem.behavioral.visitor;

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

/**
 * @Auther 20173
 * @Date 2019-4-15 14:34
 * @Des TODO
 **/
public class Test {

    public static void main(String[] args) {
        List courseList = new ArrayList<>();

        FreeCourse freeCourse = new FreeCourse();
        freeCourse.setName("SpringMvc课程");

        CodingCourse codingCourse = new CodingCourse();
        codingCourse.setName("Java设计模式 -- By Ck");
        codingCourse.setPrice(399);

        courseList.add(freeCourse);
        courseList.add(codingCourse);

        for (Course course : courseList){
            course.accept(new Visitor());
        }
    }
}

你可能感兴趣的:(java基础,设计模式,(java版),设计模式,(java版))