From the course: Complete Guide to Java Design Patterns: Creational, Behavioral, and Structural

Unlock this course with a free trial

Join today to access over 25,300 courses taught by industry experts.

Use a proxy to create objects on demand

Use a proxy to create objects on demand

I'm going to use the proxy pattern to optimize my app that gives suggestions to users based on the songs they've listened to. So the first thing I'm going to do is I'm going to make a proxy class that will make sure the expensive setup is only done the first time the object is used. So I'm going to create a new Java class and I'm going to call it RecommendationsProxy. And this class is going to implement the recommendations interface. So I'm going to add implements Recommendations. And this class is going to have a field of type recommendations as well. So I'm going to say private Recommendations recommendations; and then I need to override the showRecommendations methods. So I'm going to say @Override and then public void showRecommendations and I need to pass in a user object. So in this method, I'm going to check if the recommendations field has already been initialized. If not, then I'll create a new one and the expense of database calls will be done. If it's already been created,…

Contents