When we create objects, new is often considered, and can be used to create type design patterns. In this chapter we explain the use and advantages of the abstract factory model.
1 abstract Factory mode, from the design point of view, fully follow the opening and closing principle, when the program to expand the time, do not have to modify the original code, just on the original basis to add. This requires that both factories and products need to be abstracted by interfaces.
The following code asks the student interface and the specific implementation of the AB student and the factory interface and the production AB student's specific factory implementation.
Public interface Studentinterface {
public void Privateproperty ();
}
public class Studenta implements studentinterface{
@Override
public void Privateproperty () {
//TODO auto-generated method stub
System.out.println ("Student A");
}
}
public class STUDENTB implements studentinterface{
@Override
public void Privateproperty () {
//TODO auto-generated method stub
System.out.println ("Student B");
}
}
///////////////////////////////////////////////////////////////////////////////////
Public interface Factoryinterface {
public Studentinterface createstudent ();
}
public class Factorystudenta implements factoryinterface{
@Override
public Studentinterface createstudent () {
//TODO auto-generated method stub
return new Studenta ();
}
}
public class FACTORYSTUDENTB implements factoryinterface{
@Override
public Studentinterface createstudent () {
//TODO auto-generated method stub
return new STUDENTB ();
}
}
///////////////////////////////////
Test
public class Testabstractfactory {
public static void Main (string[] args) {
//TODO auto-generated method stub
factoryinterface facc=new factorystudentc ();
studentinterface stuc=facc.createstudent ();
Stuc.privateproperty ();
}
}
2 If we need to add a C student to our program, we simply define a C student class to implement the student interface and implement a factory interface to create a factory that generates student C objects.
public class STUDENTC implements studentinterface{
@Override
public void Privateproperty () {
//TODO auto-generated method stub
System.out.println ("Student C");
}
}
public class FACTORYSTUDENTC implements factoryinterface{
@Override
public Studentinterface createstudent () {
//TODO auto-generated method stub
return new STUDENTC ();
}
}
From the code, we can obviously realize that when the need to expand the program, we do not need to modify the previous code, only two implementation class, you can complete the code expansion function, completely follow the software design of the open and close principle, is not very cool?
Design Patterns-Abstract Factory mode