Works with dependency inversion, which states that low level objects should not depend on high level objects Mainly used when objects follow a given sequence to perfom a task but the tasks are implemented differently in every object
//the abstract class, note that the manufacture function calls the abstract methods
public abstract class GeneralManufacturingProcess {
public abstract void assembly();
public abstract void test();
public abstract void pack();
public abstract void storage();
public void manufacture() {
this.assembly();
this.test();
this.pack();
this.storage()
}
}
public class Laptop extends GeneralManufacturingProcess {
public void assembly(){
//assembles laptop
}
public void test () {
//tests laptops
}
public void pack() {
//packs laptops
}
public void store() {
//stores laptop
}
}
public class App {
public static void main(String [] args) {
GeneralManufacturingProcess laptop = new Laptop();
laptop.manufacture();
}
}
Used with Open Closed Principle. Interface depended upon by client is defined in either Abstract class or Interface, and implementations are provided by classes extending or implementing the interface.
public abstract class Employee {
abstract void performDuties();
}
public class Doctor extends Employee {
private void performDiagnosis () { //perform diagnosis }
private void prescribeDrugs () { //prescribe drugs }
public void performDuties () {
performDiagnosis();
prescribeDrugs();
}
}
public class HospitalManagement {
public void callUpon(Employee employee) {
employee.performDuties();
}
}
public class App {
public static void main(String... args) {
Employee doctor = new Doctor();
new HospitalManagement().callUpon(doctor);
}
}
Note: Read more about Strategy anad Template design Patterns in order to refine notes