Understanding the use of Java interface interface

Many people are more confused, why use interfaces. In my personal understanding, an interface is actually a set of protocols, a set of contracts, a contract between framework developers and users. Framework developers/architects promise that as long as you comply with my contract, that is, the realization of interface, then I can definitely support your extension class. When the framework designer believes that this class needs to be flexibly extended to meet the needs, while providing a default solution, this contract is proposed for users to expand. You can look at the following example, it is easier to understand the meaning of the interface definition. Framework designers allow users to extend the framework, but users cannot modify it by themselves, and must comply with a set of guidelines and a contract for the framework to function properly.


/**
 * @author zsf
 */
public class Framework {
	/**
	 * Framework initialization, the framework initialization strategy supports framework users to expand by themselves
	 * Use DefaultStrategy by default
	 * @param initStrategy interface class
	 */
	public void init(InitStrategy initStrategy)throws Exception{
		if(initStrategy == null){//If the initialization strategy is empty, use the default initialization strategy
			initStrategy = new DefaultStrategy();
		try {
			initStrategy.init();
		}
		catch (Exception e)
		{
			throw new Exception("Framework initialization exception");
		}
		}
	}
	
	public interface InitStrategy{
		public void init();
	}
	
	/**
	 * Default initialization strategy
	 */
	class DefaultStrategy implements InitStrategy{
		@Override
		public void init() {
			System.out.println("Default init strategy!");
		}
	}
	
	public static void main(String[] args) {
		initByDefaultInitStrategy();
		initByUserInitStrategy();
	}
	
	/**
	 * Initialize the default policy
	 */
	public static void initByDefaultInitStrategy(){
		Framework framework = new Framework();
		try {
			framework.init(null);
		} catch (Exception e) {
			e.printStackTrace ();
		}
	}
	
	/**
	 * Initialize user expansion strategy
	 */
	public static void initByUserInitStrategy(){
		Framework framework = new Framework();
		InitStrategy userStrategy = new UserInitStrategy();
		try {
			framework.init(userStrategy);
		} catch (Exception e) {
			e.printStackTrace ();
		}
	}
	
	/**
	 * User-defined policies
	 */
	static class UserInitStrategy implements InitStrategy{
		@Override
		public void init() {
			System.out.println("User's InitStrategy!");
		}
	}
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326269191&siteId=291194637