当前位置:网站首页>Some thoughts on callback

Some thoughts on callback

2022-06-09 03:26:00 The cat is not here

UI problem

  • In recent months, I have also made several small games , There are some problems .
  • I didn't do anything at first UI frame , But each UI Interfaces need to be opened , such as Start interface Of Start button Click to open Choose the level Interface .
  • Select the level button in the interface and click it to open the game interface .
  • When I didn't write a framework , Every UI There should be one inside the interface Open() and Close Method , And in order to call these methods , I need them to quote each other , namely
  • StartPanel Save the SelectPanel References to ,SelectPanel Save the GamePanel The interface of 【 I didn't set one UICenter General control class of 】
  • And each UI It needs an initialization process ,Init(),UI The interface needs to be initialized Button binding The function of , Generally speaking Button binding only needs to be done once
  • also ,UI Interface

Callback

  • There are three forms of callback ,
  • Set the callback function as Parameters In the form of ,
void DoSomeThing(int param, Action callback)
{
    
	
	callback.Invoke();
}
  • Subscriber pattern
public Event OnValueChanged;

publiv void ChangeGravity(int val){
    

	OnValueChanged.Invoke(val)
}
  • The difference between the above two is , The subscriber model is for more people , The callback only faces one ,

  • I also have such a puzzle .

// When I wrote the code, I already knew that the game interface should be opened after the function is executed 
// So I have two ways to deal with it  
void DoSomething(){
    
	...
	UICenter.Inst.OpenGamePanel();
}

Action callback = ()=>{
    
	UICenter.Inst.OpenGamePanel();
}
void DoSomething(callback){
    
	...
	callback.Invoke();
}
  • The form of transfer function is mostly used in a well encapsulated class , Interfaces exposed when used by others . That means you don't know what other people want , But keep such an interface for others to use .
  • If you write your own code , Know what to do next , Just write it directly in the function . This can also avoid GC

Interface confusion

  • The interface itself is a contract for others , It is for others to use .
  • It has the same effect as virtual function rewriting

interface IPoolContext
{
    
	void OnSpawn();
	void OnCreate();
}
abstract class Pool{
    
	
	virtual OnSpawn(){
     }
	
	void Spawn(IPoolContext context)
	{
    
		OnSpawn();
		context.OnSpawn();
	}
}
  • You can see above ,OnSpawn The function itself is used in Pool Self , namely The moment he created the object , One is used to generate objects Generated time , These are two events .
原网站

版权声明
本文为[The cat is not here]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206090323092525.html