Is griefing by mobs in Minecraft really random?
Solution 1:
I'm not aware of any there being any "infrastructure targeting" code in Minecraft.
The situations you describe however, seem to have three possible explanations:
The random number generator hates you. This is a known phenomenon dating all the way back to early dice games. Simply put, the random number generator appears to actively work to destroy you. Short of making a shrine to the RNG gods, no solution to this problem is known.
Selective memory. You are simply remembering the times you were horribly griefed more vividly than the times mobs spawned out in the open where you could easily take them on, even if they are equally common.
Death from above. The first two situations you gave sound like you were in an enclosed, partially lit cave. This type of environment would increase the spawn chance in other nearby areas. In such a scenario, mobs using "Death from Above" tactics is for more likely, especially in abandoned mine-shafts. The Enderman case you describe just sounds like bad luck (See point 1).
Solution 2:
There is no such code, it's completely random.
It looks like the "troll-engine" is playing with you (or maybe it's Herobrine's work... nobody knows).