Model is introduced

An abstract class defines a template that allows subclasses to redefine specific steps of an algorithm without changing its structure.

Example (Buying goods)

The process of buying goods goes through the selection of goods, payment, logistics, and receipt.

Start by defining an abstract class for the purchase process

Public abstract class BaseBuyGoodsTemplate {** ** select ** @return */ protected abstract void chooseGoods(); /** * payGoods ** @return */ protected void payGoods(); /** * @return */ protected void postGoods(); /** * receiveGoods ** @return */ protected void receiveGoods(); public final void buyGoods() { chooseGoods(); payGoods(); postGoods(); receiveGoods(); }}Copy the code

Platform A buys goods

@Service public class ABuyGoodsImpl extends BaseBuyGoodsTemplate { @Override protected void chooseGoods() { System.out.println("A platform selects goods "); } @override protected void payGoods() {system.out.println (" Override protected void payGoods "); } @override protected void postGoods() {system.out.println ("A "); } @override protected void receiveGoods() {system.out.println ("A platform receiveGoods "); }}Copy the code

B platform to buy goods

@Service public class BBuyGoodsImpl extends BaseBuyGoodsTemplate { @Override protected void chooseGoods() { System.out.println("B platform select goods "); } @override protected void payGoods() {system.out.println ("B "); } @override protected void postGoods() {system.out.println ("B "); } @override protected void receiveGoods() {system.out.println ("B "); }}Copy the code

test

public static void main(String[] args) {
    BaseBuyGoodsTemplate a = new ABuyGoodsImpl();
    a.buyGoods();
    BaseBuyGoodsTemplate b = new BBuyGoodsImpl();
    b.buyGoods();
}
Copy the code

The advantages and disadvantages

advantages

  1. Encapsulate the invariant part, and the variable part can be expanded by itself;
  2. Extract common code, developer maintenance is more convenient.
  3. The parent class controls the behavior, and the child class implements it.

disadvantages

Each implementation requires a subclass, and later the system gets bigger and bigger