The code:
Connection con = DriverManager.getConnection(Url, "username", "password");
This is a Factory Pattern. The manager creates the proper concrete Connection
class based on the URL passed in.
Connection
itself is an interface (javadoc) that all of the concrete connection classes implement. MySQL, Postgres, Oracle, whatever... they are all Connection classes. The DriverManager selects the right one of those and creates it.
How does the DriverManager know? The Driver classes register themselves with the Driver when they are loaded by the class loader. When the driver goes through asking "who responds to this URL" it invokes the acceptsURL
method in each driver and the one that responds gives it a connection back when called with connect
.
Once you have a Connection
object from the Driver
(that knows how to talk to the database the driver works with) it is then able to create a statement or execute a query against that database that returns back a result set.
The specifics of these are up to the driver to implement. You've just got interfaces to these way that it works. All of the ResultSets and Statements and Connections (and Drivers) work the same way from your point of view, though how they connect to the cursor and database behind the scenes may be different. But that doesn't matter. You've got an interface and they all work the same way.
These are all instances of Factory Patterns. Factory, Abstract Factory and Factory Method may be a useful read on the matter. Other Patterns are described Examples of GoF Design Patterns in Java's core libraries. You may also find This lecture on Factory Pattern to be useful (its got the classic 'pizza' example).
As these are Patterns (and I intentionally write that with a capital 'P'), you will find these solutions used again and again in similar ways throughout programs. Once you recognize that you are dealing with a Factory, you will likely be able to work with it more efficiently.