Java Design Patterns as I Understand
1. Factory mode
What is the factory pattern?
Mapping to reality is that there is such a factory that produces a lot of products. Different customers need different products. All customers only need to tell the factory what they need, and the factory will produce what. In the factory pattern of Java, a product is an object, that is, there is such a class, and what object is needed is created.
Implementation of the Factory Pattern
There are several ways to achieve, there are factory method pattern, abstract factory pattern and so on. Here is a demo of a commonly used abstract factory pattern.
There is a factory that produces computer accessories (Abstract Factory Pattern)
1. Create an abstract factory
public abstract class AbstractComputerFactory {
public abstract ComputerCPU produceComputerCPU();
public abstract MainBoard produceMainBoard();
public abstract HardDisk produceHardDisk();
}
2, the specific realization of the factory
public class ComputerFactory extends AbstractComputerFactory {
@Override
public ComputerCPU produceComputerCPU() {
return new ComputerCPU();
}
@Override
public MainBoard produceMainBoard() {
return new MainBoard();
}
@Override
public HardDisk produceHardDisk() {
return new HardDisk();
}
}
3. Specific computer components
CPU components:
public class ComputerCPU implements ComputerCpuInterface{
@Override
public void run() {
System.out.println("ComputerCPU.run()");
}
}
public interface ComputerCpuInterface {
void run();
}
Motherboard Components:
public class MainBoard implements MainBoardInterface {
@Override
public void run() {
System.out.println("MainBoard.run()");
}
}
public interface MainBoardInterface {
void run();
}
Hard Disk Components:
public class HardDisk implements HardDiskInterface {
@Override
public void run() {
System.out.println("HardDisk.run()");
}
}
public interface HardDiskInterface {
void run();
}
4. Test
ComputerFactory computerFactory = new ComputerFactory();
// 生产一个CPU
ComputerCPU cpu = computerFactory.produceComputerCPU();
cpu.run();
// 生产一个硬盘
HardDisk hardDisk = computerFactory.produceHardDisk();
hardDisk.run();
// 生产一个主板
MainBoard board = computerFactory.produceMainBoard();
board.run();
ps: The villain is not talented, just entered the industry not long ago, there is a wrong place, welcome the advice of Daniel.