Design pattern five, factory pattern

Factory pattern :
Define an interface for creating objects and let subclasses decide which class to instantiate. The factory method delays the instantiation of a class to its subclasses, overcomes the shortcomings of a simple factory that violates the open-closed principle, and maintains the advantages of encapsulating the object creation process.

Open-closed principle : open for expansion, closed for change

Students and volunteers inherit the Lei Feng class. The student factory and volunteer factory implement the Lei Feng factory interface. When the instantiated object needs to be changed, only the factory needs to be changed. When adding a new class, you only need to add a new factory without changing the code of the original class

//雷锋
public class LeiFeng {
    
    
    public void wash() {
    
    
        System.out.println("洗衣服");;
    }

    public void cook() {
    
    
        System.out.println("做饭");;
    }
}

public class Student extends LeiFeng {
    
    
    public Student() {
    
    
        System.out.println("我是大学生");
    }

}

public class Volunteer extends LeiFeng{
    
    
    public Volunteer() {
    
    
        System.out.println("我是志愿者");
    }
}

//雷锋工厂
public interface MyFactory {
    
    
    public LeiFeng createLeiFeng();
}

public class StudentFactory implements MyFactory{
    
    
    @Override
    public LeiFeng createLeiFeng() {
    
    
        return new Student();
    }
}

public class VolunteerFactory implements MyFactory {
    
    
    @Override
    public LeiFeng createLeiFeng() {
    
    
        return new Volunteer();
    }

    public static void main(String[] args) {
    
    
        MyFactory myFactory = new StudentFactory();  //只需要改动这句,无需像简单工厂去改变已有的类。
        LeiFeng student = myFactory.createLeiFeng();

        myFactory = new VolunteerFactory();
        LeiFeng volunteer = myFactory.createLeiFeng();
    }
}

Guess you like

Origin blog.csdn.net/weixin_45401129/article/details/114629219